android - 对 FCM 服务器的 POST-ing JSON 请求不起作用

标签 android http-post firebase-cloud-messaging android-json

我正在尝试向 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();

最佳答案

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

首先将 OkHttp 添加到应用程序 gradle.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);
}

关于android - 对 FCM 服务器的 POST-ing JSON 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39068722/

相关文章:

java - 即使应用程序未运行,也处理 onMessageReceived() 和 onTokenRefresh()

android - 从模块中的build.gradle中删除项目根目录中的文件夹

android - Google NodeApi.getLocalNode 何时可能返回 null?

javascript - Ajax 的数据和 fetch API 的主体有什么区别?

spring - Spring Boot REST 中的自定义媒体类型导致 HttpMediaTypeNotSupportedException

javascript - Firebase 云消息未发送到设备

android - Kotlin/Android Studio-如何将变量从替代乐趣传递到应用程序的其余部分?

android - SecurityException : Parcel. readException 来自谷歌分析代码

swift - Swift 中的 HTTP POST 请求

android - NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID) 不适用于 Oreo Firebase 通知