我正在尝试发送和接收 JSON GCM 消息,但在客户端它似乎总是以 UTF8 的形式出现。
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
Print.logInfo("In HttpURLConnection: " + contentType + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
return conn;
}
在服务器上,UTF8 消息是: 在 HttpURLConnection: application/x-www-form-urlencoded;charset=UTF-8registration_id=APA91...&delay_while_idle=0&collapse_key=Test&time_to_live=2419200&data.Data1=Value+1&data.Data2=Value+2&data .Data3=值+3
并且 JSON 消息是:在 HttpURLConnection: application/json{"delay_while_idle":false,"collapse_key":"Test","data":{"Data1":"Value 1","Data2":"Value 2", "Data3":"Value 3"},"time_to_live":2419200,"registration_ids":["APA91..."]}
多播结果 MulticastResult(multicast_id=5036...,total=1,success=1,failure=0,canonical_ids=0,results: [[ messageId=0:1362.. ]]:
两条消息都在客户端成功接收,但我无法识别 json 格式。
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String inAction = intent.getAction();
// check to see if it is a message
if (inAction.equals("com.google.android.c2dm.intent.RECEIVE")) {
// if your key/value is a JSON string, extract and parse it using JSONObject
String json_info = intent.getExtras().getString("data");
if (json_info != null) {
try {
JSONObject jsonObj = new JSONObject(json_info);
payload = jsonObj.get("Data1") + "\n"
+ jsonObj.get("Data2")+ "\n"
+ jsonObj.get("Data3");
}
catch (JSONException e) {
// do nothing
return;
}
}
else {
payload = intent.getStringExtra("Data1") + "\n"
+ intent.getStringExtra("Data2")+ "\n"
+ intent.getStringExtra("Data3");
}
}
}
在这两种情况下 json_info 都是空的。我在运行 apache/tomcat 的服务器上使用 java servlet。
请帮忙。非常感谢