GoogleCloudMessaging未经授权错误401(Android作为服务器) [英] GoogleCloudMessaging Unauthorized Error 401 (Android as a server)
问题描述
我想用GCM。作为一个特殊的情况下,我使用Android设备作为我的第三方服务器发送消息给设备。我加入了以下code,但我得到未授权错误401。在这里,我只是试图复制PHP服务器code的机器人。
JAVA code的不工作 - 返回错误401
// HTTP POST请求
私人无效sendPost()抛出JSONException,ClientProtocolException,IOException异常{
最后弦乐SERVICE_URL =https://android.googleapis.com/gcm/send;
的InputStream的InputStream = NULL;
字符串结果=;
最后弦乐REGISTRATION_ID ="APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg" ;
最后弦乐API_KEY =AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18;
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httpPost =新HttpPost(SERVICE_URL);
INT iresponse;
SDS
字符串base64En codedCredentials = Base64.en codeToString(API_KEY.getBytes(UTF-8),Base64.NO_WRAP);
//通知服务器有关内容的类型
httpPost.addHeader(授权,关键=+ base64En codedCredentials);
JSON字符串=;
的JSONObject的JSONObject =新的JSONObject();
jsonObject.accumulate(registration_ids,REGISTRATION_ID);
//转换的JSONObject以JSON为String
JSON = jsonObject.toString();
//设置JSON来StringEntity
StringEntity SE =新StringEntity(JSON);
//设置httpPost实体
httpPost.setEntity(SE);
httpPost.setHeader(接受,应用/ JSON);
httpPost.setHeader(内容型,应用/ JSON);
//执行POST请求到指定的URL
HTT presponse HTT presponse = httpclient.execute(httpPost);
。iresponse = HTT presponse.getStatusLine()的getStatus code();
的System.out.println(iresponse);
//得到响应,为InputStream
的InputStream = HTT presponse.getEntity()的getContent()。
// InputStream转化为字符串
如果(的InputStream!= NULL)
结果= convertInputStreamToString(InputStream的);
的System.out.println(结果);
}
私有静态字符串convertInputStreamToString(InputStream中的InputStream)抛出IOException异常{
BufferedReader中的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中));
串线=;
字符串结果=;
而((行= bufferedReader.readLine())!= NULL)
结果+ =行;
inputStream.close();
返回结果;
的PHP code
< HTML>
< HEAD>
<冠军>在线PHP脚本执行< /标题>
< /头>
<身体GT;
< PHP
$ API_KEY =AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18;
$ registrationIDs = array("APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg") ;
$ URL ='https://android.googleapis.com/gcm/send';
$领域=阵列(
registration_ids'=> $ registrationIDs,
'数据'=>阵列(信息=>喜),
);
$标题=阵列(
授权:键='。 $ API_KEY,
内容类型:应用程序/ JSON);
$ CH = curl_init();
curl_setopt($ CH,CURLOPT_URL,$网址);
curl_setopt($ CH,CURLOPT_POST,真正的);
curl_setopt($ CH,CURLOPT_HTTPHEADER,$头);
curl_setopt($ CH,CURLOPT_RETURNTRANSFER,真正的);
curl_setopt($ CH,CURLOPT_SSL_VERIFYPEER,假);
curl_setopt($ CH,CURLOPT_SSL_VERIFYHOST,假);
curl_setopt($ CH,CURLOPT_POSTFIELDS,json_en code($域));
$结果= curl_exec($ CH);
curl_close($ CH);
回声$结果;
?>
< /身体GT;
< / HTML>
在上面的Java code API_KEY是浏览器键,REGISTRATION_IDis由谷歌云服务器返回的ID。同样的事情正在使用服务器密钥进行测试。
我发现在code两个问题是
1.您要发送的连接codeD API密钥
2.你是张贴在键值对的形式的数据,需要张贴JSON数据
下面是修改后的code这是工作的罚款
私人无效sendPost()抛出异常{
//下面是一个很好的教程,如何发布JSON数据
//http://hmk$c$c.com/android-send-json-data-to-server/
最后弦乐REGISTRATION_ID ="APA91bHH4iNCFdWUIXSHRXV3hsBeF8IU0ZElts9AXaHItDfRdRld-kwkVx69EFYZePPuLOW1hTkUCmAwyTeGdoirr25KJ3RG1AikGbBzsvqaPCLLz9YYCwPDuB6xUupVKmllNoTn2v0BRTTkC6OS_i8zerATtBP3gg" ;
最后弦乐API_KEY =AIzaSyARQTvQ5pRYEbW-9V98uDHNnn10Rwffx18;
字符串URL =https://android.googleapis.com/gcm/send;
HttpClient的客户端=新DefaultHttpClient();
HttpPost后=新HttpPost(URL);
JSONObject的mainData =新的JSONObject();
尝试 {
JSONObject的数据=新的JSONObject();
data.putOpt(MESSAGE1,测试味精);
data.putOpt(消息2,测试..................);
JSONArray regIds =新JSONArray();
regIds.put(REGISTRATION_ID);
mainData.put(registration_ids,regIds);
mainData.put(数据,数据);
Log.e(测试,JSON数据=+ mainData.toString());
}赶上(JSONException E){
// TODO自动生成的catch块
e.printStackTrace();
}
StringEntity本身=新StringEntity(mainData.toString());
post.setEntity(SE);
post.addHeader(授权,关键=+ API_KEY);
post.addHeader(内容类型,应用/ JSON);
HTT presponse响应= client.execute(后);
Log.e(测试,
响应code =+ Integer.toString(response.getStatusLine()的getStatus code()));
的BufferedReader RD =新的BufferedReader(
新的InputStreamReader(response.getEntity()的getContent()));
StringBuffer的结果=新的StringBuffer();
串线=;
而((行= rd.readLine())!= NULL)
{
result.append(线);
}
Log.e(测试,响应+ result.toString());
}
I am trying to send message to device using GCM .As a special case I am using android device as my third party server. I have added following code but I am getting "Unauthorized Error 401" . Here I am simply trying to replicate php server code in android .
JAVA CODE WHICH IS NOT WORKING - RETURNING ERROR 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
<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 . Same thing is tested using server key .
Two problems which i found in your code is
1. you are sending an encoded API key
2. you are posting a form data in key value pair , need to post json data
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());
}
这篇关于GoogleCloudMessaging未经授权错误401(Android作为服务器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!