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(); }