【问题标题】:GoogleCloudMessaging Unauthorized Error 401 (Android as a server)GoogleCloudMessaging Unauthorized Error 401(Android 作为服务器)
【发布时间】:2014-04-09 04:44:42
【问题描述】:

我正在尝试使用 GCM 向设备发送消息。作为一种特殊情况,我使用 android 设备作为我的第三方服务器。我添加了以下代码,但我收到 "Unauthorized Error 401" 。这里我只是想在android中复制php服务器代码。

无法运行的 JAVA 代码 - 返回错误 401。

    // HTTP POST request
private void sendPost() throws JSONException, ClientProtocolException, IOException{
    final String SERVICE_URL = "https://android.googleapis.com/gcm/send";
    InputStream inputStream = null;
    String result = "";
    final String REGISTRATION_ID ="APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg" ;
    final String API_KEY = "AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18";
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(SERVICE_URL);
    int iresponse; 
    sds  
            String base64EncodedCredentials = Base64.encodeToString(API_KEY.getBytes("UTF-8"), Base64.NO_WRAP);
    // inform the server about the type of the content
    httpPost.addHeader("Authorization", "key=" + base64EncodedCredentials);

    String json = "";

    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("registration_ids", REGISTRATION_ID);

    // convert JSONObject to JSON to String
    json = jsonObject.toString();

    // set json to StringEntity
    StringEntity se = new StringEntity(json);

    // set httpPost Entity
    httpPost.setEntity(se);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    // Execute POST request to the given URL
    HttpResponse httpResponse = httpclient.execute(httpPost);
    iresponse = httpResponse.getStatusLine().getStatusCode();
    System.out.println(iresponse);
    // receive response as inputStream
    inputStream = httpResponse.getEntity().getContent();

    // convert inputstream to string
    if(inputStream != null)
    result = convertInputStreamToString(inputStream);

    System.out.println(result);

}

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

工作 PHP 代码

<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$api_key = "AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18";
$registrationIDs = array("APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg") ;
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => "Hi" ),
);

$headers = array(
'Authorization: key=' . $api_key,
'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER , false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST , false );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);

echo $result;
?>
</body>
</html>

在上面的 Java 代码中,API_KEY 是浏览器密钥,而 REGISTRATION_ID 是 Google Cloud Server 返回的 id。使用服务器密钥测试同样的事情。

【问题讨论】:

  • 首先,永远不要像这样分享你的 API_KEY。
  • @Kedarnath。以后我不会了。这是一个测试应用程序。一段时间后我会删除它。你能帮我找出我在上面的java代码中做错了什么吗?

标签: java php android https google-cloud-messaging


【解决方案1】:

我在您的代码中发现的两个问题是
1. 您正在发送一个编码的 API 密钥
2.您是在键值对中发布表单数据,需要发布json数据

下面是修改后的代码,运行良好

private void sendPost() throws Exception {

    //Below is a good tutorial , how to post json data
    //http://hmkcode.com/android-send-json-data-to-server/

    final String REGISTRATION_ID ="APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg" ;
    final String API_KEY = "AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18";



    String url = "https://android.googleapis.com/gcm/send";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    JSONObject mainData = new JSONObject();
    try {
        JSONObject data = new JSONObject();
        data.putOpt("message1", "test msg");
        data.putOpt("message2", "testing..................");
        JSONArray regIds = new JSONArray();
        regIds.put(REGISTRATION_ID);
        mainData.put("registration_ids", regIds);
        mainData.put("data", data);
        Log.e("test","Json data="+mainData.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StringEntity se = new StringEntity(mainData.toString());
    post.setEntity(se);
    post.addHeader("Authorization", "key="+API_KEY);
    post.addHeader("Content-Type", "application/json");
    HttpResponse response = client.execute(post);
    Log.e("test" ,
            "response code ="+Integer.toString(response.getStatusLine().getStatusCode()));
    BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null)
    {
        result.append(line);
    }
    Log.e("test","response is"+result.toString());
}

【讨论】:

    【解决方案2】:

    我已经使用以下代码解决了这个问题:

    SendNotificationToControllingApp.java

    package gcm.sendnotificationtocontrollingapp;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import org.apache.http.client.ClientProtocolException;
    import org.json.JSONException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class SendNotificationToControllingApp {
    
        // HTTP POST request
        public void sendPost(String notification) throws JSONException, ClientProtocolException, IOException{
    
            try{
                //final String REGISTRATION_ID ="APA91bFsyAvE8grzYU3D22RCe07_qegdn6ZHEFMoNbPpk327YUE2wXleyyi0vyn8IWFADEdxq2IOv0up0aIJ9MEDYF065gOI0Os-aNL4puNhLop0502_Pbeq0l72peXACM8S82N4vmwd4saTW2KJGq4TjTrhMCRYVg" ;
                final String REGISTRATION_ID = "APA91bGirysw8BO9GI5F1Fs2kKzru_2ptGLTX_7RJdhphAA6ebEBvJ64vBraFLgG6CNBmEuy7qEMW-APrwegM81UWfjbI2HliHeRRDsQk6iLiUeWSSIINYTvJgs2-tays4E8ORgejcviNx43jrXx1lJa5i54aZtw59w"; //Registration ID of client device.
                //final String API_KEY = "AIzaSyByuglfRAx9ndiIB5eLRr64Dhhgr5lnul0WY"; //browser key .
                final String API_KEY = "AIzaSyDN5Jq-nUasrChRjNvWQrHRTlh_6u2SeJ0"; //server key .
    
                Content content = new Content();
                content.addRegId(REGISTRATION_ID);
                content.createData("data", notification);
                URL url = new URL("https://android.googleapis.com/gcm/send");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key="+API_KEY);
                conn.setDoOutput(true);
                ObjectMapper mapper = new ObjectMapper();
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                mapper.writeValue(wr, content);
                int responseCode = conn.getResponseCode();
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Response Code : " + responseCode);
    
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
    
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
    
                System.out.println(response.toString());
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    }
    

    内容.java

     package gcm.sendnotificationtocontrollingapp;
    
    import java.io.Serializable;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    
    public class Content implements Serializable {
    
        private List<String> registration_ids;
        private Map<String,String> data;
    
        public void addRegId(String regId){
            if(registration_ids == null)
                registration_ids = new LinkedList<String>();
            registration_ids.add(regId);
        }public void createData(String title, String message){
            if(data == null)
                data = new HashMap<String,String>();
    
            data.put("title", title);
            data.put("message", message);
        }
    
    
        public List<String> getRegistration_ids() {
            return registration_ids;
        }
    
        public void setRegistration_ids(List<String> registration_ids) {
            this.registration_ids = registration_ids;
        }
    
        public Map<String, String> getData() {
            return data;
        }
    
        public void setData(Map<String, String> data) {
            this.data = data;
        }
    }
    

    注意:将 registrationIds 、apikey 和项目编号替换为您的项目知识。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多