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

时间:2011-07-30 17:15:18

标签: java header httprequest host apache-httpcomponents

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

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

生成的请求对象未使用值

设置强制“主机”标头
Host: myapp.com

任何提示?

2 个答案:

答案 0 :(得分:9)

我的错。实际上,DefaultHttpClient会根据HTTP规范的要求添加Host标头。

我的问题是由于我之前添加的其他自定义标头,其值已结束 “\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);

在HTTP请求中生成以下标头序列:

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

Host: www.example.com

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);

这会产生:

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

答案 1 :(得分:3)

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