简体   繁体   English

GoogleCloudMessaging未经授权错误401(Android作为服务器)

[英]GoogleCloudMessaging Unauthorized Error 401 (Android as a server)

I am trying to send message to device using GCM .As a special case I am using android device as my third party server. 我正在尝试使用GCM向设备发送消息。在特殊情况下,我将android设备用作第三方服务器。 I have added following code but I am getting "Unauthorized Error 401" . 我添加了以下代码,但出现“未经授权的错误401”。 Here I am simply trying to replicate php server code in android . 在这里,我只是想在android中复制php服务器代码。

JAVA CODE WHICH IS NOT WORKING - RETURNING ERROR 401 . 无法工作的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;

WORKING PHP CODE 工作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>

In the above Java code API_KEY is browser key and REGISTRATION_IDis the id returned by Google Cloud Server . 在上面的Java代码中,API_KEY是浏览器密钥,REGISTRATION_ID是Google Cloud Server返回的ID。 Same thing is tested using server key . 使用服务器密钥测试相同的事物。

Two problems which i found in your code is 我在您的代码中发现的两个问题是
1. you are sending an encoded API key 1.您正在发送编码的API密钥
2. you are posting a form data in key value pair , need to post json data 2.您要在键​​值对中发布表单数据,需要发布json数据

Below is the modified code which is working fine 下面是修改好的代码,可以正常工作

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

I have resolved this problem using following code : 我已经使用以下代码解决了这个问题:

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

Content.java Content.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;
    }
}

NOTE : Replace registrationIds ,apikey and project number with your projects intellactuals . 注意:用您的项目智能替换registrationIds,apikey和项目编号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM