如何在JAVA中使用HTTP发送标头

时间:2015-01-27 10:48:49

标签: java apache-httpclient-4.x

我有这个命令。

# 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发送标题。

1 个答案:

答案 0 :(得分:0)

根据您的curl示例,这应该是您的Authorization标题:

httppost.addHeader("Authorization", "key=AIza*********YUI");

这可以解决您的问题。我刚刚使用引用的documentation确认了此标头。