这是我创建 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();
但是当发送一些请求时,用户代理是空,这是日志:
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 进行值注入(inject)之前实例化 httpClient,因此实例化 httpClient 时 userAgent 值为 null。
感谢您的精神努力,
我是一名优秀的程序员,十分优秀!