你的位置:首页 > Java教程

[Java教程]使用GCM(谷歌云消息)发送消息 (服务器端http协议)


1. http请求格式  

 https://gcm-http.googleapis.com/gcm/send Content-Type:application/json Authorization:key=API_KEY {  "to": "/topics/foo-bar",  "data": {   "message": "This is a GCM Topic Message!",   } }

2. 返回格式示例

1).发送给单个IDs消息

{ "multicast_id": 216, "success": 3, "failure": 3, "canonical_ids": 1, "results": [  { "message_id": "1:0408" },  { "error": "Unavailable" },  { "error": "InvalidRegistration" },  { "message_id": "1:1516" },  { "message_id": "1:2342", "registration_id": "32" },  { "error": "NotRegistered"} ]}

2).发送给topic

//Success example:{ "message_id": "10"}//failure example:{ "error": "TopicsMessageRateExceeded"}

3. java代码

    try {      // Prepare JSON containing the GCM message content. What to send and where to send.      JSONObject jGcmData = new JSONObject();      // Where to send GCM message.      jGcmData.put("to", "/topics/global");      JSONObject jData = new JSONObject();      jData.put("message", "天王盖地虎,小鸡炖蘑菇");      // What to send in GCM message.      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=" + API_KEY);      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) {      e.printStackTrace();    }