我正在尝试使用GCM向设备发送消息。作为一个特例,我使用Android设备作为我的第三方服务器。我添加了以下代码,但我收到“未经授权的错误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。使用服务器密钥测试相同的内容。
答案 0 :(得分:2)
我在你的代码中发现的两个问题是
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());
}
答案 1 :(得分:0)
我使用以下代码解决了这个问题:
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
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;
}
}
注意:用您的项目intellctuals替换registrationIds,apikey和项目编号。