如何使用Retrofit打Firebase HTTP协议?

时间:2019-03-01 17:50:14

标签: firebase-cloud-messaging retrofit retrofit2

我要o在https://fcm.googleapis.com/fcm/send上发布数据 以及Retrofit中的两个标头

要发送的数据

{
  "data" : {
    "title": "My Title",
    "content": "My message"
  },

  "to": "cKA7LrjBQ6s:APA91bHtY6RBwZ4KZvxbl9VNZMVKz5_NDbE2dP3zgrhJNBSAKDyfOAbfxEi8pnAwc82pzLoGEZImZBv9MXvoBSJy6c0790oqUIYLECCU5WZVcGeSJJNECX5bsLMutYrSPjLSDffP5N3u"
}

1 个答案:

答案 0 :(得分:1)

这很简单。创建以下类。

public interface RestInterface {

    @Headers({
        "Content-Type: application/json",
        "Authorization: key=<YOUR_FCM_SERVER_KEY_HERE>"
    })
    @POST("fcm/send")
    Call<ResponseBody> sendNotification(@Body NotificationBody body);

}

用实际的FCM服务器密钥替换<YOUR_FCM_SERVER_KEY_HERE>

public class NotificationBody {

    @SerializedName("data")
    private Data data;

    @SerializedName("to")
    private String to;

    public NotificationBody(Data data, String to) {
        this.data = data;
        this.to = to;
    }

}

以上POJO类将在运行时生成外部JSONObject。下面的POJO类将生成data JSONObject。

public class Data {

    @SerializedName("title")
    private String title;

    @SerializedName("content")
    private String content;

    public Data(String title, String content) {
        this.title = title;
        this.content = content;
    }


}

最后在下面的Activity / Fragment类中使用上面的代码,

String title = "My Title";
String content = "My message";
String to = "cKA7LrjBQ6s:APA91bHtY6RBwZ4KZvxbl9VNZMVKz5_NDbE2dP3zgrhJNBSAKDyfOAbfxEi8pnAwc82pzLoGEZImZBv9MXvoBSJy6c0790oqUIYLECCU5WZVcGeSJJNECX5bsLMutYrSPjLSDffP5N3u";

Data data = new Data(title, content);
NotificationBody body = new NotificationBody(data, to);


RestInterface api = ....;

Call<ResponseBody> call = api.sendNotification(body);
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {

        // do whatever you want to do

    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e("TAG", "Error: ", t);
    }
});

不要忘记将翻新BASE_URL设置为https://fcm.googleapis.com/