我正在尝试从设备向设备发送消息,而不使用任何第三方服务器(我确实将其用于其他部分)。 我正在使用HTTP请求直接从设备发送到gcm服务器。
这是我所做的。
try {
HttpPost httppost;
try {
httppost = new HttpPost(
"https://android.googleapis.com/gcm/send");
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
httppost.setHeader("Authorization", "key=512218918480");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("registration_id", id));
postParams.add(new BasicNameValuePair("data.mode",
"exampleContentOfYourMessage"));
postParams.add(new BasicNameValuePair("m",
"exampleContentOfYourMessage"));
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity entity;
try {
httppost.setEntity(new UrlEncodedFormEntity(postParams, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
try {
response = httpClient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
entity = response.getEntity();
if (entity != null
&& response.getStatusLine().getStatusCode() == 200) {
return true;
} else {
Log.e("Tag", "No Connection");
return false;
}
} catch (Exception e) {
Log.e("grokkingandroid",
"IOException while sending registration id", e);
}
return false;
}
返回
02-24 00:19:13.772: W/DefaultRequestDirector(9913): Authentication error: Unable to respond to any of these challenges: {}
因此看起来像https的身份验证错误。我需要向gcm服务器发送更多内容吗?
我也知道使用这种方法的缺陷。我的id会在应用程序中安全性降低。我无法发送大量数据等等。