向 FCM 服务器发送 JSON 请求不起作用

Posted

技术标签:

【中文标题】向 FCM 服务器发送 JSON 请求不起作用【英文标题】:POST-ing JSON request to FCM server isn't working 【发布时间】:2016-08-21 20:48:01 【问题描述】:

我正在尝试向 Firebase 服务器发送 FCM 请求,正如 FCM 文档所说,它应该是带有 JSON 数据的 POST 请求。这是示例。

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

 "data": 
    "score": "5x1",
    "time": "15:10"
  ,
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."

那么任何人都可以给出一个正确的代码来发送带有这个 JSON 数据的 POST 请求吗?

这是我尝试过的,但它不起作用

AsyncT.java

package com.example.artin.pushnotifications;

import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

class AsyncT extends AsyncTask<Void,Void,Void> 

    @Override
    protected Void doInBackground(Void... params) 

        try 
            URL url = new URL("https://fcm.googleapis.com/fcm/send"); //Enter URL here
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
            httpURLConnection.setRequestProperty("Authorization","key=AIzaSyDZx9l_Izta9AjVS0CX70ou8OjbDVVGlHo");
            httpURLConnection.connect();

            JSONObject jsonObject = new JSONObject();
            JSONObject param = new JSONObject();
            param.put("Hii","there");

            jsonObject.put("data",param);
            jsonObject.put("to", "dXazhmeFSSU:APA91bG23o75zeNOCb7pY-OCQG4BsGbY-YZrSnDrvLWv1");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
         catch (JSONException e) 
            e.printStackTrace();
        

        return null;
    



当按下按钮时我执行它

AsyncT asyncT = new AsyncT();
asyncT.execute();

【问题讨论】:

这么多重复,你还没有提供你已经尝试过的东西。 Volley 很好,但OkHttp 也很好。见这里***.com/a/36160967/2308683 Sending POST data in Android的可能重复 它在邮递员中有效,但在代码中无效 cricket_007 OkHttp 终于成功了。谢谢) 【参考方案1】:

我使用了 OkHttp,现在它可以工作了。如果有人需要,这里是代码。

首先将 OkHttp 添加到应用程序的 graddle.build 中

compile 'com.squareup.okhttp3:okhttp:3.4.1'

这里是发送POST Json请求的方法

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    Call post(String url, String json, Callback callback) 
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .addHeader("Authorization","key=YourApiKey")
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    

然后创建 Json 对象并在你想要的地方调用它。

try 
    JSONObject jsonObject = new JSONObject();
    JSONObject param = new JSONObject();
    param.put("Hii", "there");
    param.put("Hours", "12:50");
    jsonObject.put("data", param);
    jsonObject.put("to", "TokenOfTheDevice");
    post("https://fcm.googleapis.com/fcm/send", jsonObject.toString(), new Callback() 
                @Override
                public void onFailure(Call call, IOException e) 
                    //Something went wrong
                

                @Override
                public void onResponse(Call call, Response response) throws IOException 
                    if (response.isSuccessful()) 
                        String responseStr = response.body().string();
                        Log.d("Response", responseStr);
                        // Do what you want to do with the response.
                     else 
                        // Request not successful
                    
                
            
    );
 catch (JSONException ex) 
    Log.d("Exception", "JSON exception", ex);

【讨论】:

【参考方案2】:

这可以使用 AsyncTask、HTTPRequest 来完成

    private class PostTask extends AsyncTask<String, String, String> 

      String Url = "//fcm.googleapis.com/fcm/send"

      @Override
      protected String doInBackground(String... data) 
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Url);

        try 
          //add data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair("data", data[0]));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          //execute http post
          HttpResponse response = httpclient.execute(httppost);

         catch (ClientProtocolException e) 

         catch (IOException e) 

        
      
    

这可以使用 new PostTask().execute();

【讨论】:

HttpClient 已被 android 弃用 @Aram Sheroyan 是的,HttpClient 已弃用,但您可以使用它。只需将 compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' 添加到您的 build.gradle 依赖项中。 @Stanojkovic 那不是completely correct @cricket_007 你是对的,但即使没有 useLibrary 'org.apache.http.legacy' 它仍然有效,Android Studio 不会给出“无法解析符号...”的消息

以上是关于向 FCM 服务器发送 JSON 请求不起作用的主要内容,如果未能解决你的问题,请参考以下文章

向 FCM API 发送请求时收到无效的 JSON 有效负载

无法从服务器向 FCM url 发送请求(相同的代码在本地 pc 上工作)

iOS 中的 JSON 发布不起作用(.NET 服务器)

Google FCM 服务器:200 但未向手机发送通知

FCM 链接在桌面通知中不起作用

FCM 通知在 OREO 中不起作用