Java - DefaultHttpClient and Host header [Apache HttpComponent]

I am sending multiple HTTP requests through DefaultHttpClient. The problem is that the "Host" header is never set in the request. For example, by running 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 created request object does not set the required "Host" header with the value:

 Host: myapp.com 

Any tips?

+6
source share
2 answers

My mistake. In fact, DefaultHttpClient do adds the Host header, as required by the HTTP specification.

My problem arose because of another custom header that I added before whose value ended with " \r\n ". This will invalidate all 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); 

which generated the following sequence of headers in the HTTP request:

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

A space between the X-Custom-Header and Host invalidates the Host header. Fixed:

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

This generates:

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

Just set the host header in the request using addHeader .

+1
source

Source: https://habr.com/ru/post/893945/


All Articles