如何使用okhttp更改连接请求的header

How to change the header of connect request with okhttp

我安装了一个拦截器,它在我的 java okhttp4 客户端上设置自定义用户代理字符串。

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 header。如何更改 CONNECT User-Agent header?

我终于通过添加自定义代理验证器解决了我的问题

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();
    }
}