I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll look at how to set a custom header with the HttpClient.

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

2. Set Header on Request – Before 4.3

You can set any custom header on a request with a simple setHeader call:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
client.execute(request);

As you can see, we’re setting the Content-Type directly on the request to a custom value – JSON.

3. Set Header on Request – 4.3 and above

HttpClient 4.3 has introduced a new way of building requests – the RequestBuilder. To set a header, we will use the same, setHeader method – on the builder:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(SAMPLE_URL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);

4. Set Default Header on the Client – 4.3 and above

Instead of setting the Header on each and every request, you can also configure it as a default header on the Client itself:

Header header = new BasicHeader(
  HttpHeaders.CONTENT_TYPE, "application/json");
List<Header> headers = Lists.newArrayList(header);
HttpClient client = HttpClients.custom()
  .setDefaultHeaders(headers).build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(SAMPLE_URL).build();
client.execute(request);

This is extremely helpful when the header needs to be the same for all requests – such as a custom application header.

5. Conclusion

This article illustrated how to add an HTTP header to one or all requests sent via the Apache HttpClient.

The implementation of all these examples and code snippets can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
oleg
Guest

It is generally recommended to set Content-Type on request entity. HttpClient will automatically populate entity meta-headers based on properties of enclosed request entity

Eugen Paraschiv
Guest

Well, it probably depends on the specific usecase – can you point me to an example where the Content-Type is automatically set? For example – when sending a StringEntity – if the header is not set explicitly – HttpClient is going to predictably set it to text/plain – which is not ideal.

oleg
Guest

HttpClient adds ContentType an ContentEncoding values to the request message exactly as defined by the enclosed request entity [1]

[1] http://hc.apache.org/httpcomponents-core-4.3.x/httpcore/xref/org/apache/http/protocol/RequestContent.html#114

Eugen Paraschiv
Guest

Sounds good, but I was referring to an actual example where the header is indeed automatically set. As far as I can see here – this is not necessarily the case. The case looks to be that – if the entity itself has a content type already set, then the client will use it – but other than that – nothing else is done.

Shilpa
Guest

I tried using method addHeader but I got error saying method addHeader is undefined for the type HttpGet.

Can you please help me how to use method addheader/setHeader?

Eugen Paraschiv
Guest

Hey Shilpa – I just ran the code using the addHeader call again and everything runs fine. So – if you want me to take a look at your specific usecase, please raise an issue on github with the code sample, or a pull request – and I’d be happy to see what the problem is. Cheers,
Eugen.

Shilpa
Guest

Thanks Eugen for your reply. Can you please share your imports? I have my code on github but its internal to my employer. let me try to share the code via public link.

Eugen Paraschiv
Guest

Hey Shilpa – so, all the code samples for the article (including the exact imports) are in the project I pointed to at the end of the article. Hope they help. Cheers,
Eugen.

varun
Guest

Hi Eugen,

Was wondering if you have tried or seen any example or have clue how to use HttpClient within Spring controller to simulate FORM submit using Http.POST.

Use Case:
User fills up basic details on JSP and submit.
Controller fetches associated details based on input from JSP.
Controller calls external URL from within Spring controller and send required parameters as form POST.

JSP –> Spring controller –> HTTP POST on external URL.

I understand Spring’s “redirect:” , “RedirectView” but the problem is they convert request as GET and query parameters gets appended to URL.

Eugen Paraschiv
Guest
Hey Varum – if I understand your scenario fully, you need to basically proxy the form submission. You have 2 options – first, you could look into a proxy solution that’s not necessarily Spring focused – that might allow you to more easily to the submission. Second, you can, very carefully – simulate the submission request. So, from the Controller, you use the HttpClient and do a request similar to your original submission. It’s a very manual process, with quite a bit of complexity, so I wouldn’t necessarily recommend doing it, but if you need to, it’s technically doable. Best… Read more »
wpDiscuz