如何使用RETROFIT库发布原始JSON对象

时间:2019-07-01 16:34:29

标签: java android firebase firebase-cloud-messaging retrofit

我尝试使用Postman并使用相同的JSON对象进行测试,但效果很好,但是当我使用翻新库时却无法正常工作。

我尝试将JSON对象放入Pojo类中,但仍然无法正常工作。

通知服务类别

public interface NotificationService {
    @Headers({
            "Content-Type:"+ApiConstants.CONTENT_TYPE,
            "Authorization:"+ApiConstants.SERVER_KEY
    })
    @POST(ApiConstants.SEND)
    Call<ResponseBody> sendNotification(@Body String body);

}

APICONSTANTS类别

public class ApiConstants {
    public static final String SERVER_KEY = "key=mykey";
    public static final String SEND = "send";
    public static final String BASE_URL = "https://fcm.googleapis.com/fcm/";
    public static final String CONTENT_TYPE = "application/json";
    public static final String NOTIFICATION = "{\n" +
            "    \"to\": \"/topics/MISSING\",\n" +
            "    \"data\": {\n" +
            "        \"extra_information\": \"This is some extra information\"\n" +
            "    },\n" +
            "    \"notification\": {\n" +
            "        \"title\": \"She pressed the button\",\n" +
            "        \"text\": \"She misses you\",\n" +
            "        \"click_action\": \"MAINACTIVITY\"\n" +
            "    }\n" +
            "}";
}

主要活动

private void buttonIsPressed() {
        RetrofitClient retrofitClient;
        retrofitClient = RetrofitClient.getInstance();


        Call<ResponseBody> call = retrofitClient.getNotificationService().sendNotification(ApiConstants.NOTIFICATION);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody result = response.body();
                String gs = new Gson().toJson(result);
                Log.d("MainActivity", "response = " + gs);
            }

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

我正尝试在按下按钮时向某些特定用户发送通知。据我所知,唯一不起作用的是使用Call<ResponseBody> sendNotification(@Body String body)

时输入了错误的内容

1 个答案:

答案 0 :(得分:0)

您应该创建一个模型类

Just _

创建MyRequestBodyModel的新实例并传递您的值

public class MyRequestBodyModel {

    @SerializedName("id")
    private int id;

    @SerializedName("name")
    private String name;

}

将此模型的实例设置为改装调用方法的参数

MyRequestBodyModel model = new MyRequestBodyModel();
model.id = 1;
model.name = "john";