gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:12:42 31 4
gpt4 key购买 nike

我正在使用 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
}

因此,我尝试将“to”替换为“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();
}

}

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

最佳答案

您不需要 [] 来包围您的 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();

关于java - 如何编写 Google Cloud Messaging 的 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166362/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com