1

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.

{"collapse_key":"new-test-notification","data":{"info1":"info_1","info3":"info_3","info2":"info 2"},"registration_ids":["APA91bG3bmCSltzQYl_yOcjG0LPcR1Qemwg7osYJxImpSuWZftmmIjUGH_CSDG3mswKuV3AAb8GSX7HChOKGAYHz1A_spJus5mXFtfOrK0fouBD7QBpKnfc_ly0t3S8vSYWRjuGxtXrt"]}
Ryan Gray
  • 824
  • 8
  • 17
  • when i had this issue with the old C2DM it meant that i was not registered to the google service, in the developer console check: 1. did you create a project in your console ? 2. did you enable google cloud service for your project in the developer console ? 3.i assume it's trival that u posses a valid API key. – codeScriber Jun 30 '12 at 11:26
  • Can you post the JSON string of the request, just print out what the output of temp1.toJSONString() is. – azgolfer Jun 30 '12 at 23:41
  • Just updated with JSON String. Thanks, still have this problem – Ryan Gray Jul 03 '12 at 13:55
  • Make sure you are doing this on a separate thread, by the way :) – Alex Lockwood Jul 03 '12 at 13:59
  • I understand what you mean but this isn't from my App. It's a Java project created for GCM testing. No seperate threads needed – Ryan Gray Jul 03 '12 at 14:01
  • @codeScriber Yes I've done all those things. Appreciate the reply – Ryan Gray Jul 03 '12 at 14:02
  • 1
    @Ryan, how about printing out the error body GCM sent you? According to them 400 is JSON error and more info will be included in the response message. Try printing out conn.getInputStream() or conn.getErrorStream(). – azgolfer Jul 03 '12 at 21:45

3 Answers3

1

I solved it using a different approach so it must have been my original implementation.

List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("username",username));
        list.add(new BasicNameValuePair("deviceId",regId));
        list.add(new BasicNameValuePair("deviceType","AndroidPhone"));
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("example.url.com");
        post.setEntity(new UrlEncodedFormEntity(list));
        ResponseHandler<String> handler = new BasicResponseHandler();
        HttpResponse response = client.execute(post);
        String responseString = handler.handleResponse(response);
        JSONObject jsonResponse = new JSONObject(responseString);
Ryan Gray
  • 824
  • 8
  • 17
  • What is response in handler.handleResponse(response)? IS it a callback function to deal with the response from server? Can you please post the sample code for that? Thanks – CuriousCoder Aug 27 '12 at 19:06
0

I'm reading here that you should use your 'Key for browser apps' GCM with PHP (Google Cloud Messaging) (in comments)

Community
  • 1
  • 1
Klaasvaak
  • 5,430
  • 12
  • 43
  • 67
0

Try to reproduce the error using curl or another command-line tool so we can eliminate the possibility that there's a bug in your java that we're all missing.

Rob Starling
  • 3,760
  • 2
  • 20
  • 38