如何在 JAVA 中使用 HTTP 发送 Header
How to send Header using HTTP in JAVA
我有这个命令。
# curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"ABC\"]}"
它正在我的设备中发送推送通知。现在我正在尝试 java 发送它,但我的代码不起作用。
String body = "{\"registration_ids\":[\"ABC\"]}";
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(body, "UTF-8");
httppost.addHeader("Content-Type","application/json");
httppost.addHeader("Authorization: key", "AIza*********YUI");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
System.out.println("strresponse = "+strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我很困惑我错过了什么。这个文档 http://developer.android.com/google/gcm/http.html#request 告诉我需要用 body.
发送 header
根据您的 curl
示例,这应该是您的 Authorization
header:
httppost.addHeader("Authorization", "key=AIza*********YUI");
这应该可以解决您的问题。我刚刚用引用的 documentation.
确认了这个 header
我有这个命令。
# curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"ABC\"]}"
它正在我的设备中发送推送通知。现在我正在尝试 java 发送它,但我的代码不起作用。
String body = "{\"registration_ids\":[\"ABC\"]}";
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(body, "UTF-8");
httppost.addHeader("Content-Type","application/json");
httppost.addHeader("Authorization: key", "AIza*********YUI");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
System.out.println("strresponse = "+strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我很困惑我错过了什么。这个文档 http://developer.android.com/google/gcm/http.html#request 告诉我需要用 body.
发送 header根据您的 curl
示例,这应该是您的 Authorization
header:
httppost.addHeader("Authorization", "key=AIza*********YUI");
这应该可以解决您的问题。我刚刚用引用的 documentation.
确认了这个 header