簡體   English   中英

無法使用Google App Engine(GAE)連接到Google Cloud Messaging(GCM)服務器

[英]Can't connect to Google Cloud Messaging (GCM) server using Google App Engine (GAE)

我正在嘗試為我的應用設置谷歌雲消息,我正在為我的服務器使用Google App Engine。 我有我的API密鑰,但我似乎無法連接到谷歌雲消息服務器。 這是我的代碼。

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();
        }

當我查看日志時,標題正在設置正確。 但是,我收到一個錯誤

org.apache.http.impl.client.DefaultRequestDirector tryConnect:連接到目標主機時捕獲的I / O異常(java.net.SocketException):權限被拒絕:嘗試在未經許可的情況下訪問被阻止的收件人。 (映射-IPv4)的

我已經在Google API控制台中啟用了Google雲消息傳遞,並且我已經多次檢查了我的API密鑰。 我不知道為什么我會被拒絕。 我在戰爭中需要一個罐子或者我必須在清單中放一些東西嗎?

感謝您閱讀!! 標記

我有同樣的問題,我正在使用類似於你正在使用的東西。

  1. 我必須在我的GAE應用程序上啟用計費(您可能已經擁有,但我不知道我必須這樣做)
  2. 閱讀https://developers.google.com/appengine/docs/java/sockets/和https://developers.google.com/appengine/docs/java/urlfetch/

因此,我之前看起來像你的代碼如下所示:

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);

我也用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的回答也幫助了我。 在實施他建議的內容后,通知將被發送到設備,而無需為我的GAE應用程序啟用計費。 以下是我的實現,以防萬一,可能對有相同問題的人有用:

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());
    }
}

希望這會幫助別人......

最簡單的方法是使用gcm-server.jar (你可以從這里獲得)。

然后,您需要發送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);

這是gradle依賴: compile 'com.google.gcm:gcm-server:1.0.0'mvnrepository url

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM