新しい GCM サービスを使用して C2DM を置き換えるために、アプリの特定の部分をオーバーホールしています。テスト用に Java プログラムから JSON 要求を作成し、応答を読み取りたいだけです。今のところ、JSON リクエストで書式設定の問題を見つけることができず、Google サーバーは常にコード 400 を返します。これは、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());
リクエストをEclipseコンソールに出力して、フォーマットを確認します
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());
}
}
エラー401が発生するため、APIキーが正しいと確信しているため、Googleのドキュメントに記載されています。JSONは初めてですが、シンプルなので分かりやすいです。コード 400 を常に受け取る理由について何か考えがある人はいますか?
更新: gcm で提供されている Google サーバーのサンプル クラスをテストしたので、問題は私のコードにあるはずです。
{"collapse_key":"new-test-notification","data":{"info1":"info_1","info3":"info_3","info2":"info 2"},"registration_ids":["APA91bG3bmCSltzQYl_yOcjG0LPcR1Qemwg7osYJxImpSuWZftmmIjUGH_CSDG3mswKuV3AAb8GSX7HChOKGAYHz1A_spJus5mXFtfOrK0fouBD7QBpKnfc_ly0t3S8vSYWRjuGxtXrt"]}