Android HttpsURLConnection and JSON for new GCM
Posted
by
Ryan Gray
on Stack Overflow
See other posts from Stack Overflow
or by Ryan Gray
Published on 2012-06-29T14:54:27Z
Indexed on
2012/07/03
9:16 UTC
Read the original article
Hit count: 404
I'm overhauling certain parts of my app to use the new GCM service to replace C2DM. I simply want to create the JSON request from a Java program for testing and then read the response. As of right now I can't find ANY formatting issues with my JSON request and the google server always return code 400, which indicates a problem with my JSON. http://developer.android.com/guide/google/gcm/gcm.html#server
JSONObject obj = new JSONObject();
obj.put("collapse_key", "collapse key");
JSONObject data = new JSONObject();
data.put("info1", "info_1");
data.put("info2", "info 2");
data.put("info3", "info_3");
obj.put("data", data);
JSONArray ids = new JSONArray();
ids.add(REG_ID);
obj.put("registration_ids", ids);
System.out.println(obj.toJSONString());
I print my request to the eclipse console to check it's formatting
byte[] postData = obj.toJSONString().getBytes();
try{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpsURLConnection.setDefaultHostnameVerifier(new JServerHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + API_KEY);
System.out.println(conn.toString());
OutputStream out = conn.getOutputStream();
// exception thrown right here. no InputStream to get
InputStream in = conn.getInputStream();
byte[] response = null;
out.write(postData);
out.close();
in.read(response);
JSONParser parser = new JSONParser();
String temp = new String(response);
JSONObject temp1 = (JSONObject) parser.parse(temp);
System.out.println(temp1.toJSONString());
int responseCode = conn.getResponseCode();
System.out.println(responseCode + "");
} catch(Exception e){
System.out.println("Exception thrown\n"+ e.getMessage());
}
}
I'm sure my API key is correct as that would result in error 401, so says the google documentation. This is my first time doing JSON but it's easy to understand because of its simplicity. Anyone have any ideas on why I always receive code 400?
update: I've tested the google server example classes provided with gcm so the problem MUST be with my code.
© Stack Overflow or respective owner