Custom User-Agent in Apache HttpClient – Apache HttpClient中的自定义用户代理

最后修改: 2013年 12月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

这个快速教程将展示如何使用Apache HttpClient发送一个自定义的User-Agent标头

2. Setting User-Agent on the HttpClient

2.在HttpClient上设置User-Agent

2.1. Before HttpClient 4.3

2.1.在HttpClient 4.3之前

When working with older versions of Http Client (pre 4.3), setting the value of the User-Agent was done via a low level API:

当使用旧版本的Http Client(4.3之前)时,设置User-Agent的值是通过一个低级别的API完成的。

client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 Firefox/26.0");

The same can be done via a higher level API as well – without dealing with the raw http.useragent property:

同样的事情也可以通过更高级别的API完成–无需处理原始http.useragent属性。

HttpProtocolParams.setUserAgent(client.getParams(), "Mozilla/5.0 Firefox/26.0");

A full example would look like this:

一个完整的例子是这样的。

@Test
public void whenClientUsesCustomUserAgent_thenCorrect() 
  throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(client.getParams(), "Mozilla/5.0 Firefox/26.0");

    HttpGet request = new HttpGet("http://www.github.com");
    client.execute(request);
}

2.2. After HttpClient 4.3

2.2.在HttpClient 4.3之后

In recent version of the Apache client (after 4.3), the same is achieved in a much cleaner way, via the new fluent APIs:

在最近的Apache客户端版本中(4.3之后),通过新的流畅的API,以更简洁的方式实现了同样的功能。

@Test
public void whenRequestHasCustomUserAgent_thenCorrect() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();
    instance.execute(new HttpGet("http://www.github.com"));
}

3. Setting User-Agent on Individual Requests

3.在个人请求上设置用户代理

A custom User-Agent header can also be set on individual requests, not on the entire HttpClient:

一个自定义的User-Agent头也可以在单个请求上设置,而不是在整个HttpClient上。

@Test
public void givenDeprecatedApi_whenRequestHasCustomUserAgent_thenCorrect() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClients.custom().build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
    instance.execute(request);
}

4. Conclusion

4.结论

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

这篇文章说明了你如何使用HttpClient来发送带有自定义User-Agent头的请求–例如模拟特定浏览器的行为。

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

所有这些例子和代码片段的实现可以在我的github项目中找到 – 这是一个基于Eclipse的项目,所以它应该很容易导入并按原样运行。