Server side GCM returns error 400

荒凉一梦 提交于 2019-12-20 04:23:36

问题


I am tring to implement GCM. I wrote a test code to understand how it works, but I keep getting error 400 in the response.

I'm writing in Java (JDK 7).

I followed this toturial on the subject. I modified the given code there, and changed the use of ObjectMapper to Gson.

This is my code for the Data object:

public class Data {
   private ArrayList<String> registration_ids;

   public Data() {
      this.registration_ids = new ArrayList<String>();  
      this.registration_ids.add("APA91...");  // There is the real device registration id here.
   }
}

*I saw in the server reference that in HTTP protocol, I can send a message just with registration_ids. (All other are optional)

Here is the code to send the message:

public static void post(String apiKey, Data data){

    try{

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body

        // 5.1 Convert object to JSON
        Gson gson = new Gson();
        Type type = new TypeToken<Data>() {}.getType();

        String json = gson.toJson(data, type);

        System.out.println(json);
        // The printed string is
        // {"registration_ids":["APA91..."]}
        // with the correct registration id of my device.


        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());


        // 5.3 Copy Content "JSON" into
        wr.writeUTF(json);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I know that error 400 means a json problem, but I tried many variations for the data I'm sending, and none of them worked (I created the string manually, without gson, in these tests).

This is the error message I'm receiving:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://android.googleapis.com/gcm/send at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1675) at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1673) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1671) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1244) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at POST2GCM.post(POST2GCM.java:64) at App.main(App.java:8) Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://android.googleapis.com/gcm/send at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338) at POST2GCM.post(POST2GCM.java:59) ... 1 more

Can you please help me with this issue? Thank you very much, Yuval.


回答1:


The problem was in DataOutputStream.writeChars() and DataOutputStream.writeUTF().

Thanks to the link given by @Koh, I changed the write command in the post function to:

wr.write(json.getBytes("UTF-8"));

Now the message is being sent successfully!



来源:https://stackoverflow.com/questions/30352133/server-side-gcm-returns-error-400

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!