服务器端 GCM returns 错误 400

Server side GCM returns error 400

我正在尝试实施 GCM。 我写了一个测试代码来了解它是如何工作的,但我总是在响应中收到错误 400。

我正在写 Java (JDK 7).

我关注了 this 关于这个主题的教程。 我在那里修改了给定的代码,并将 ObjectMapper 的使用更改为 Gson。

这是我的数据对象代码:

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.
   }
}

*我在server reference中看到,在HTTP协议中,我只用registration_ids就可以发送消息。 (其他都是可选的)

这是发送消息的代码:

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();
    }
}

我知道错误 400 意味着 json 问题,但我对发送的数据尝试了多种变体,其中 none 有效(我手动创建了字符串,没有 gson ,在这些测试中)。

这是我收到的错误消息:

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.run(HttpURLConnection.java:1675) at sun.net.www.protocol.http.HttpURLConnection.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

你能帮我解决这个问题吗? 非常感谢你, 尤瓦尔.

问题出在 DataOutputStream.writeChars() 和 DataOutputStream.writeUTF() 中。

感谢@Koh给出的link,我将post函数中的write命令改为:

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

消息发送成功!