【发布时间】:2016-05-19 20:35:08
【问题描述】:
我正在使用 gcm 将通知推送到一台或多台设备,但是我经常收到错误消息:“发件人 ID 不匹配”。
这是我的代码:
public static void post(String apiKey){
try{
// prepare JSON
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "{good luck}");
jGcmData.put("to","token ID");
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
} catch (IOException e) {
System.out.println("Unable to send GCM message. "+e);
}
}
另外,当我使用jGcmData.put("to","/topics/foo-bar");而不是jGcmData.put("to","token ID");时,可以成功发送通知。但是,我想要将通知推送到选定的设备。
【问题讨论】:
标签: java server google-cloud-messaging