gpt4 book ai didi

java - Apache HttpClientBuilder.create().setUserAgent(...) 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:32 26 4
gpt4 key购买 nike

这是我创建 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。

感谢您的精神努力,

关于java - Apache HttpClientBuilder.create().setUserAgent(...) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59226467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com