如何编写Google Cloud Messaging的POST请求?

时间:2015-08-23 11:52:37

标签: java json google-cloud-messaging

我正在使用Google Cloud Messaging向客户发送消息,但我想将这些消息发送给多个收件人而不是一个。 以下是我目前发送的请求的简单主体:

https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=API_KEY
{
"to" : "REGISTRATION_TOKEN",
"notification" : {
 "sound" : "default",
 "badge" : "1",
 "title" : "default",
 "body"  : "Test"
 },
"content_available" : true
}

所以我尝试将"替换为"通过" registration_ids"然后提供id列表,但我得到一个回复​​说" registration_ids字段不是JSONArray"。

这是我写的Java代码:

public static void sendGCM(String tag, String message, ArrayList<String> listeDeviceIds) {
    String registrationIds = listeDeviceIds.get(0);
    for (int i=1; i<listeDeviceIds.size(); i++){
        registrationIds = registrationIds+","+listeDeviceIds.get(i);
    }
    JSONArray jsonArray = new JSONArray();
    jsonArray.addAll(listeDeviceIds);
    String json ="{\"registration_ids\" : \"["+jsonArray+"]\",\"notification\" : {\"sound\" : \"default\",\"badge\" : \"1\",\"title\" : \"default\",\"body\"  : \"Test\"},\"content_available\" : true}"; 
    try{
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
        request.addHeader(new HTTPHeader("Content-Type","application/json")); 
        request.addHeader(new HTTPHeader("Authorization", "key="+API_KEY));
        request.setPayload(json.getBytes("UTF-8"));
        HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
    }
    catch(Exception e){
        e.printStackTrace();
    }

}

提供收件人列表的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您不需要[]来围绕您的jsonArray。您应该将前7行代码更改为以下内容:

JSONArray jsonArray = new JSONArray();
for (String id : listeDeviceIds) {
   jsonArray.put(id);
}
String json ="{\"registration_ids\" : "+jsonArray+",\"notification\" : {\"sound\" : \"default\",\"badge\" : \"1\",\"title\" : \"default\",\"body\"  : \"Test\"},\"content_available\" : true}";

或者,使用JSONObjectJSONArray构建json有效负载也更好:

        String json = "";

        JSONObject jsonObject = new JSONObject();

        JSONArray regIdArray = new JSONArray();
        for (String id : listeDeviceIds) {
            regIdArray.put(id);
        }
        jsonObject.accumulate("registration_ids", regIdArray);

        JSONObject notificationObject = new JSONObject();
        notificationObject.accumulate("sound", "default");
        notificationObject.accumulate("badge", "1");
        notificationObject.accumulate("title", "default");
        notificationObject.accumulate("body", "test");
        jsonObject.accumulate("notification", notificationObject);

        jsonObject.accumulate("content_available", true);

        json = jsonObject.toString();