Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

This quick tutorial will show how to send a custom User-Agent header using Apache HttpClient.

2. Setting User-Agent on the HttpClient

We can set the User-Agent while configuring the client itself:

HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();

A full example would look like this:

@Test
void whenClientUsesCustomUserAgent_thenCorrect() throws IOException {
    CloseableHttpClient client = HttpClients.custom()
        .setUserAgent("Mozilla/5.0 Firefox/26.0")
        .build();
    final HttpGet request = new HttpGet(SAMPLE_URL);

    String response = client.execute(request, new BasicHttpClientResponseHandler());
    logger.info("Response -> {}", response);
}

3. Setting User-Agent on Individual Requests

A custom User-Agent header can also be set on individual requests, adding more flexibility to our client:

@Test
void whenRequestHasCustomUserAgent_thenCorrect() throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    final HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");

    String response = client.execute(request, new BasicHttpClientResponseHandler());
    logger.info("Response -> {}", response);
}

4. Conclusion

This article illustrated how you can use the HttpClient to send requests with a custom User-Agent header – for example, to simulate the behaviour of a specific browser.

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.

Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – HTTP Client (eBook) (cat=Http Client-Side)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.