[英]Can't connect to Google Cloud Messaging (GCM) server using Google App Engine (GAE)
I am trying to set up google cloud messaging for my app, and I am using Google App Engine for my server. 我正在尝试为我的应用设置谷歌云消息,我正在为我的服务器使用Google App Engine。 I have my API key but I can't seem to make a connection to the google cloud messaging servers.
我有我的API密钥,但我似乎无法连接到谷歌云消息服务器。 Here is my code.
这是我的代码。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://android.googleapis.com/gcm/send");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("registration_id", regId));
nameValuePairs.add(new BasicNameValuePair("data.message", messageText));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
post.setHeader("Authorization", "key=*MY_API_KEY_HERE*");
post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
Header[] s=post.getAllHeaders();
System.out.println("The header from the httpclient:");
for(int i=0; i < s.length; i++){
Header hd = s[i];
System.out.println("Header Name: "+hd.getName()
+" "+" Header Value: "+ hd.getValue());
}
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
When I look at the log the headers are being setup right. 当我查看日志时,标题正在设置正确。 However, I get an error that says
但是,我收到一个错误
org.apache.http.impl.client.DefaultRequestDirector tryConnect: I/O exception (java.net.SocketException) caught when connecting to the target host: Permission denied: Attempt to access a blocked recipient without permission.
org.apache.http.impl.client.DefaultRequestDirector tryConnect:连接到目标主机时捕获的I / O异常(java.net.SocketException):权限被拒绝:尝试在未经许可的情况下访问被阻止的收件人。 (mapped-IPv4)
(映射-IPv4)的
I've turned google cloud messaging on in the Google APIs Console and I've checked my API key a bunch of times. 我已经在Google API控制台中启用了Google云消息传递,并且我已经多次检查了我的API密钥。 I have no clue why I'm getting rejected.
我不知道为什么我会被拒绝。 Is there a jar I need in the war or something I have to put in the manifest?
我在战争中需要一个罐子或者我必须在清单中放一些东西吗?
Thanks for reading this!! 感谢您阅读!! Mark
标记
I had the same problem and I was using something similar to what you are using. 我有同样的问题,我正在使用类似于你正在使用的东西。
Therefore my code which looked like yours before now looks like following: 因此,我之前看起来像你的代码如下所示:
String json ="{}";
URL url = new URL("https://android.googleapis.com/gcm/send");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.addHeader(new HTTPHeader("Content-Type","application/json"));
request.addHeader(new HTTPHeader("Authorization", "key=<>"));
request.setPayload(json.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
I was also implementing GCM with GAE, and I had an error like this: 我也用GAE实现了GCM,我遇到了这样的错误:
com.google.apphosting.api.ApiProxy$FeatureNotEnabledException: The Socket API will be enabled for this application once billing has been enabled in the admin console.
Nikunj answer helped me too. Nikunj的回答也帮助了我。 After implementing what he suggested, notifications are delivered to the device, without need for enabling billing for my GAE App.
在实施他建议的内容后,通知将被发送到设备,而无需为我的GAE应用程序启用计费。 Here is my implementation, just in case, may be useful for someone with same problem:
以下是我的实现,以防万一,可能对有相同问题的人有用:
private void sendNotificationRequestToGcm(List<String> registrationIds) {
LOG.info("In sendNotificationRequestToGcm method!");
JSONObject json = new JSONObject();
JSONArray jasonArray = new JSONArray(registrationIds);
try {
json.put("registration_ids", jasonArray);
} catch (JSONException e2) {
LOG.severe("JSONException: " + e2.getMessage());
}
String jsonString = json.toString();
LOG.info("JSON payload: " + jsonString);
com.google.appengine.api.urlfetch.HTTPResponse response;
URL url;
HTTPRequest httpRequest;
try {
//GCM_URL = https://android.googleapis.com/gcm/send
url = new URL(GCM_URL);
httpRequest = new HTTPRequest(url, HTTPMethod.POST);
httpRequest.addHeader(new HTTPHeader("Content-Type","application/json"));
httpRequest.addHeader(new HTTPHeader("Authorization", "key=" + API_KEY));
httpRequest.setPayload(jsonString.getBytes("UTF-8"));
LOG.info("Sending POST request to: " + GCM_URL);
response = URLFetchServiceFactory.getURLFetchService().fetch(httpRequest);
LOG.info("Status: " + response.getResponseCode());
List<HTTPHeader> hdrs = response.getHeaders();
for(HTTPHeader header : hdrs) {
LOG.info("Header: " + header.getName());
LOG.info("Value: " + header.getValue());
}
} catch (UnsupportedEncodingException e1) {
LOG.severe("UnsupportedEncodingException" + e1.getMessage());
} catch (MalformedURLException e1) {
LOG.severe("MalformedURLException" + e1.getMessage());
} catch (IOException e) {
LOG.severe("URLFETCH IOException" + e.getMessage());
}
}
Hope this will help someone... 希望这会帮助别人......
The easiest way is to use gcm-server.jar
(which you can get from here ). 最简单的方法是使用
gcm-server.jar
(你可以从这里获得)。
Then the code you'll need to send a GCM message will look like this : 然后,您需要发送GCM消息的代码如下所示:
Sender sender = new Sender(apiKey);
Message message = new Message.Builder()
.addData("message", "this is the message")
.addData("other-parameter", "some value")
.build();
Result result = sender.send(message, registrationId, numOfRetries);
Here's the gradle dependency: compile 'com.google.gcm:gcm-server:1.0.0'
and mvnrepository url 这是gradle依赖:
compile 'com.google.gcm:gcm-server:1.0.0'
和mvnrepository url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.