8

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Mark
  • 67,098
  • 47
  • 117
  • 162

2 Answers2

10

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
Mark
  • 67,098
  • 47
  • 117
  • 162
  • 2
    Good catch! In my case (on Android) I was Base64 encoding a header value with [`Base64.DEFAULT`](http://developer.android.com/reference/android/util/Base64.html#DEFAULT), which includes line terminators. As a result all key-value pairs coming after the custom header got messed up (couldn't even see them when running the request through a proxy). Switching to [`Base64.NO_WRAP`](http://developer.android.com/reference/android/util/Base64.html#NO_WRAP) solved my problem, as it omits all line terminators (that is, the output is one long line). – MH. Mar 17 '15 at 09:19
3

Just set the host header on the request using addHeader.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • Great answer. I was able to set a custom value for `Host` and confirm that it worked by getting http://djce.org.uk/dumprequest. That page dumps back the headers it receives, and sure enough, the value of `Host` was what I set it to (not `djce.org.uk`, which is what it would be if the Host value had not been changed). – Steve HHH Aug 20 '13 at 16:36