Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JAVA中使用HTTP发送标头_Java_Apache Httpclient 4.x - Fatal编程技术网

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

如何在JAVA中使用HTTP发送标头,java,apache-httpclient-4.x,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\

我有这个命令

# 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();
    }

我不知道我错过了什么。此文档告诉我需要发送带有正文的标题。

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

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

这将解决您的问题。我刚刚用引用的确认了这个标题。

你是什么意思,但是
但是我的代码不是
?是否有任何异常被抛出?你经历过什么结果吗?如果你不告诉我们到底出了什么问题,我们怎么帮你?