我想通过 javascript 代码发送 gcm 消息。为此,我们需要发布一个 json 对象。
url 和 json 对象格式在 gcm 文档中给出:http: //developer.android.com/google/gcm/adv.html。
出于测试目的,我编写了一个完美运行的 java 代码。但是javascript代码不起作用。如果有人有一些示例工作代码(用于 gcm 的 javascript),请发布。
String body = "registration_id=proper_id&data.number=12345678";
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
out.write(bytes);
javascript代码:
var http = new XMLHttpRequest();
var url = "https://android.googleapis.com/gcm/send";
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) { document.getElementById("target").innerHTML = http.responseText;
}
}
http.open("POST", url, false);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Authorization", "key=proper_api_key");
var data = '{ "collapse_key": "qcall","time_to_live": 108, "delay_while_idle": true,"data": {"number":"12345678"},"registration_ids":["proper_id"]}';
http.send(data);