我正在尝试使用JSON格式的应用中的第三方服务器通过GCM发送消息。 JSON字符串确实被格式化为谷歌开发页面上描述的格式..但我得到一个空字符串作为响应..任何想法为什么会发生..
这些是我的代码片段..
String send_url="https://android.googleapis.com/gcm/send";
URL url=new URL(send_url);
trace("After initialization of URl");
JSONObject send_obj=new JSONObject();
JSONObject data_obj=new JSONObject();
data_obj.put("message", "Notification Sent");
trace("data_object",data_obj);
send_obj.put("data", data_obj);
trace("Send_object",send_obj);
JSONArray reg_id_array=new JSONArray();
reg_id_array.add(reg_id);
send_obj.put("registration_ids", reg_id_array);
JSONObject check_response=SendServerRequest.sendJSONRequest(url, send_obj.toString());
}
catch (MalformedURLException | SQLException | JSONException | NullPointerException ex )
{
}
这是我的SendServerRequest类..
static JSONObject sendJSONRequest(URL url, String request)
{
HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization","the authorization key");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(request);
writer.flush();
writer.close();
return parseResponse(connection);
}
catch (IOException | NullPointerException e)
{
System.out.println("An error occurred: " + e.getMessage());
return null;
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}