通过GCM发送推送通知时连接被拒绝错误

时间:2016-01-12 15:39:46

标签: android google-cloud-messaging

您好我正在尝试使用以下代码从服务器应用程序发送推送通知但是获得“连接拒绝错误”。我正在使用服务器API密钥,也启用了用于Android的Google云消息传递。请建议。

try {  
    final String API_KEY ="server api key"; 
    String CLIENT_REG_ID ="APA91bEZD2MFH7TzMvry1UR2ezqTSAwCbqRgIZ8qXo_h559TYId29j3u2zPyHzxiZrA65tVhtPlY9O77LnLRbqJf585YmwYccBrGoQ5OjPAz4xT_JfIGJ1AEyjq9EUEhawc2V4kMrIar"; 
    final String postData = "{ \"registration_ids\": [ \"" + CLIENT_REG_ID + "\" ], " +
             "\"delay_while_idle\": true, " +
             "\"data\": {\"tickerText\":\"My Ticket\", " +
             "\"contentTitle\":\"My Title\", " +
             "\"message\": \"Test GCM message from GCMServer-Android\"}}";                      


     URL url = new URL("https://android.googleapis.com/gcm/send");
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
     urlConnection.setDoInput(true);
     urlConnection.setDoOutput(true);
     urlConnection.setRequestMethod("POST");
     urlConnection.setRequestProperty("Content-Type", "application/json");
     urlConnection.setRequestProperty("Authorization", "key=" + API_KEY);

     OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
     writer.write(postData);
     writer.flush();
     writer.close();
     outputStream.close();

     int responseCode = urlConnection.getResponseCode();
     System.out.println("response code is"+responseCode);
     InputStream inputStream;

     if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
         inputStream = urlConnection.getInputStream();
     } else {
         inputStream = urlConnection.getErrorStream();
     }

     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
     String temp, response = "";

     while ((temp = bufferedReader.readLine()) != null) {
         response += temp;
     }

} catch (IOException e) {
     e.printStackTrace();    
}

0 个答案:

没有答案