英文:
How to change the header of connect request with okhttp
问题
我安装了一个拦截器,它在我的 Java OkHttp4 客户端上设置了自定义的用户代理字符串。
```java
public class UserAgentInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
return chain.proceed(chain.request().newBuilder()
.removeHeader("User-Agent")
.addHeader("User-Agent", MYUSERAGENT);
}
}
client = new OkHttpClient.Builder()
.addNetworkInterceptor(new UserAgentInterceptor())
.build();
我使用 Fiddler 进行了检查,它似乎对请求(GET/POST)本身起作用。然而,在此之前有一个 CONNECT 请求,其仍然具有 okhttp 标头。我该如何更改 CONNECT 请求的 User-Agent 标头?
<details>
<summary>英文:</summary>
I installed an interceptor, which sets the custom useragent string on my java okhttp4 client.
public class UserAgentInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
return chain.proceed(chain.request().newBuilder()
.removeHeader("User-Agent")
.addHeader("User-Agent", MYUSERAGENT);
}
}
client = new OkHttpClient.Builder()
.addNetworkInterceptor(new UserAgentInterceptor())
.build();
I checked it with Fiddler and it seems to work with the request (GET/POST) itself. However, there is a CONNECT request beforehand which still has the okhttp header. How can I change the CONNECT User-Agent header?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/eI0EP.png
</details>
# 答案1
**得分**: 1
我通过添加自定义代理验证器最终解决了我的问题。
```java
new OkHttpClient.Builder()
.proxyAuthenticator(new MyProxyAuthenticator())
.addNetworkInterceptor(new UserAgentInterceptor());
public class MyProxyAuthenticator implements Authenticator {
@Nullable
@Override
public Request authenticate(@Nullable Route route, @NotNull Response response) throws IOException {
Request request = new JavaNetAuthenticator().authenticate(route, response);
if (request == null) {
request = new Request.Builder()
.url(route.address().url())
.method("CONNECT", null)
.header("Host", toHostHeader(route.address().url(), true))
.header("Proxy-Connection", "Keep-Alive")
.build();
}
return request.newBuilder()
.header("User-Agent", MYUSERAGENT)
.build();
}
}
英文:
I finally solved my problem by adding a custom proxy authenticator
new OkHttpClient.Builder()
.proxyAuthenticator(new MyProxyAuthenticator())
.addNetworkInterceptor(new UserAgentInterceptor());
public class MyProxyAuthenticator implements Authenticator {
@Nullable
@Override
public Request authenticate(@Nullable Route route, @NotNull Response response) throws IOException {
Request request = new JavaNetAuthenticator().authenticate(route, response);
if (request == null) {
request = new Request.Builder()
.url(route.address().url())
.method("CONNECT", null)
.header("Host", toHostHeader(route.address().url(), true))
.header("Proxy-Connection", "Keep-Alive")
.build();
}
return request.newBuilder()
.header("User-Agent", MYUSERAGENT)
.build();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论