Apache HttpClientBuilder.create().setUserAgent(...) 不工作

Apache HttpClientBuilder.create().setUserAgent(...) not working

这是我创建 HttpClient 的方式:

private String userAgent= "Non empty user agent";
private HttpClient httpClient= HttpClientBuilder.create()
    .setDefaultCookieStore(new BasicCookieStore())
    .setUserAgent(userAgent)
    .setDefaultRequestConfig(RequestConfig.custom()
        .setCookieSpec(CookieSpecs.STANDARD)
        .build())
    .setDefaultHeaders(Arrays.asList(
        new BasicHeader("Accept-Encoding", "gzip"),
        new BasicHeader("Connection", "keep-alive")))
    .build();

但是当发送一些请求时,USER AGENT 是空的,这是日志:

12:51:33.807 [http-nio-5010-exec-9] DEBUG org.apache.http.headers - http-outgoing-0 >> GET / HTTP/1.1
12:51:33.807 [http-nio-5010-exec-9] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept- Encoding: gzip
12:51:33.807 [http-nio-5010-exec-9] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: www.somehost.com
12:51:33.807 [http-nio-5010-exec-9] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: keep-alive
12:51:33.807 [http-nio-5010-exec-9] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: 

我尝试将用户代理设置为默认值 header,如下所示:

.setDefaultRequestConfig(RequestConfig.custom()
    .setCookieSpec(CookieSpecs.STANDARD).build())
.setDefaultHeaders(Arrays.asList(
    new BasicHeader("Accept-Encoding", "gzip"),
    new BasicHeader("Connection", "keep-alive"),
    new BasicHeader("User-Agent", userAgent)))
.build();

但结果相同(用户代理为空)。

这是我发送请求的方式:

HttpResponse httpResponse = httpClient.execute(new HttpGet(baseUrl));

Http 客户端的 Maven pom 依赖项:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

问题出在实例化顺序上:实际上我使用的是 SpringBoot,用户代理值是从属性文件中加载的,就是这样:

 @Value("${com.myapplication.userAgent}")
 private String userAgent;
private HttpClient httpClient= HttpClientBuilder.create()
    .setDefaultCookieStore(new BasicCookieStore())
    .setUserAgent(userAgent)
    .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
    .setDefaultHeaders(Arrays.asList(
            new BasicHeader("Accept-Encoding", "gzip"),
            new BasicHeader("Connection", "keep-alive"))
    )
    .build();

JVM 在为 userAgent 进行值注入之前实例化 httpClient,因此在实例化 httpClient 时,userAgent 值为 null。

感谢您的脑力劳动,