程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 使用GCM(谷歌雲消息)發送消息 (服務器端http協議),gcm谷歌雲

使用GCM(谷歌雲消息)發送消息 (服務器端http協議),gcm谷歌雲

編輯:JAVA綜合教程

使用GCM(谷歌雲消息)發送消息 (服務器端http協議),gcm谷歌雲


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

 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved