Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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?

like image 873
Mark Avatar asked Jul 30 '11 17:07

Mark


People also ask

Do we need to close CloseableHttpClient?

The reason is that the default client implementation returns an instance of CloseableHttpClient, which requires closing. Therefore, in our custom code, we should use the CloseableHttpClient class, not the HttpClient interface.

What is CloseableHttpClient in Java?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated. The HttpClient is an interface for this class and other classes. You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder .


1 Answers

My fault. Actually the DefaultHttpClient do adds the Host header, as required by the HTTP specification.

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:

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:

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

Host: www.example.com

The space between X-Custom-Header and Host invalidated the Host header. Fixed with:

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
like image 103
Mark Avatar answered Oct 14 '22 18:10

Mark