2013-09-08 25 views
7

Sto provando a configurare google cloud messaging per la mia app e sto utilizzando Google App Engine per il mio server. Ho la mia chiave API ma non riesco a stabilire una connessione con i server di Google Cloud. Ecco il mio codice.Impossibile collegarsi al server Google Cloud Messaging (GCM) utilizzando Google App Engine (GAE)

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

Quando guardo il registro, le intestazioni vengono configurate correttamente. Tuttavia, ottengo un errore che dice

org.apache.http.impl.client.DefaultRequestDirector tryConnect: eccezione di I/O (java.net.SocketException) catturati durante la connessione a host di destinazione: Autorizzazione negata: Tentativo per accedere a un destinatario bloccato senza autorizzazione. (mapped-IPv4)

Ho attivato il servizio di Google Cloud nella console delle API di Google e ho controllato la mia chiave API un paio di volte. Non ho idea del motivo per cui mi sto rifiutando. C'è un barattolo di cui ho bisogno in guerra o qualcosa che devo mettere nel manifest?

Grazie per aver letto questo !! Mark

+0

E 'possibile che si definito un insieme di indirizzi IP autorizzati con la tua chiave API e l'IP che stai cercando di connettere a GCM non è presente nell'elenco? – Eran

+0

No, l'accesso API è impostato su qualsiasi IP consentito. –

+0

Da dove ricevi la chiave API?Tutto quello che riesco a trovare è una coppia di chiavi. –

risposta

2

Ho avuto lo stesso problema e stavo usando qualcosa di simile a quello che stai usando.

  1. ho dovuto consentire la fatturazione sul mio GAE app (che probabilmente si ha, ma non ero consapevole del fatto che avrei dovuto)
  2. Leggi https://developers.google.com/appengine/docs/ java/prese/e https://developers.google.com/appengine/docs/java/urlfetch/

Pertanto il mio codice che sembrava come la tua prima d'ora si presenta come segue:

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

I stava anche implementando GCM con GAE, e ho avuto un errore del genere:

com.google.apphosting.api.ApiProxy$FeatureNotEnabledException: The Socket API will be enabled for this application once billing has been enabled in the admin console. 

La risposta di Nikunj ha aiutato anche me. Dopo aver implementato ciò che ha suggerito, le notifiche vengono consegnate al dispositivo, senza necessità di abilitare la fatturazione per la mia app GAE. Qui è la mia realizzazione, nel caso, può essere utile per qualcuno con lo stesso problema:

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

Spero che questo vi aiuterà qualcuno ...

-1

Il modo più semplice è quello di utilizzare gcm-server.jar (che si può ottenere da here).

Quindi il codice avrete bisogno di inviare un messaggio GCM sarà simile a questa:

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

Ecco la dipendenza Gradle: compile 'com.google.gcm:gcm-server:1.0.0' e mvnrepository url

source

Problemi correlati