我正在尝试向Google Cloud Messaging服务发送HTTP-POST。我已经设置了正确的密钥,当我使用php脚本向我的手机发送推送通知时,一切正常。
但是我的Java httpPost只返回401响应。我已按照Android Developers给出的说明进行操作,但我仍然遇到恼人的401.我是否指定了标题字段错误?
我的代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
public class Server {
public static void main(String[] args) throws IOException {
String url = "https://android.googleapis.com/gcm/send";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("registration_id=", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data=", "Type=value,Lat=58.365547,Long=8.613235,Comment=value"));
httppost.setHeader("Authorization",
"key=MY_API_AUTH_FROM_GOOGLE_API_CONSOLE_BROWSER_TOKEN");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ 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);
}
}
}
答案 0 :(得分:1)
您正在正确设置授权标头。您的API密钥可能存在问题。
您的注册ID和有效负载确实存在问题(与401错误无关)。
这是错误的:
urlParameters.add(new BasicNameValuePair("registration_id=", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data=", "Type=value,Lat=58.365547,Long=8.613235,Comment=value"));
您应该从密钥中删除=
,并且每个payload参数应以data.
开头。因此你应该:
urlParameters.add(new BasicNameValuePair("registration_id", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data.Type", "value"));
urlParameters.add(new BasicNameValuePair("data.Lat", "58.365547"));
urlParameters.add(new BasicNameValuePair("data.Long", "8.613235"));
urlParameters.add(new BasicNameValuePair("data.Comment", "value"));