I want to send a gcm message through javascript code. To do this, we need to place the json object.
The URL and format of the json object are specified in gcm docs: http://developer.android.com/google/gcm/adv.html .
For testing purposes, I wrote Java code that works great. But javascript code is not working. If anyone has a working code example (javascript for gcm) send a message.
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 code:
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);
source share