Java - DefaultHttpClient 和“Host”标头 [Apache HttpComponent]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6884719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:44:30  来源:igfitidea点击:

Java - DefaultHttpClient and "Host" header [Apache HttpComponent]

javaheaderhttprequesthostapache-httpcomponents

提问by Mark

I'm submitting multiple HTTP Requests via a DefaultHttpClient. The problem is that the "Host" header is never set in the request. For example by executing the following GET request:

我正在通过 DefaultHttpClient 提交多个 HTTP 请求。问题是“主机”标头从未在请求​​中设置。例如通过执行以下 GET 请求:

HttpUriRequest request = new HttpGet("http://www.myapp.com");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(request);

The generated request object doesn't set the mandatory "Host" header with the value:

生成的请求对象不会使用以下值设置强制性的“主机”标头:

Host: myapp.com

Any tips?

有小费吗?

回答by Mark

My fault. Actually the DefaultHttpClientdo adds the Hostheader, as required by the HTTP specification.

我的错。实际上DefaultHttpClientdo 添加了Host标头,正如 HTTP 规范所要求的那样。

My problem was due to an other custom header I was adding before whose value ended with "\r\n". This has invalidated all the subsequent headers added automatically by DefaultHttpClient. I was doing something like:

我的问题是由于我之前添加的另一个自定义标头,其值以“ \r\n”结尾。这使由 自动添加的所有后续标头无效DefaultHttpClient。我在做类似的事情:

HttpUriRequest request = new HttpGet("http://www.myapp.com");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
request.addHeader(new BasicHeader("X-Custom-Header", "Some Value\r\n");
HttpResponse httpResponse = client.execute(request);

that generated the following Header sequence in the HTTP request:

在 HTTP 请求中生成了以下 Header 序列:

GET /index.html HTTP/1.1
X-Custom-Header: Some value

Host: www.example.com

The space between X-Custom-Headerand Hostinvalidated the Hostheader. Fixed with:

X-Custom-HeaderHost使Host标题无效的空格。固定:

HttpUriRequest request = new HttpGet("http://www.myapp.com");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
request.addHeader(new BasicHeader("X-Custom-Header", "Some Value");
HttpResponse httpResponse = client.execute(request);

That generates:

这会产生:

GET /index.html HTTP/1.1
X-Custom-Header: Some value
Host: www.example.com

回答by Alex Gitelman

Just set the host header on the request using addHeader.

只需使用addHeader在请求上设置主机标头。