【问题标题】:How to change the header of connect request with okhttp如何使用 okhttp 更改连接请求的标头
【发布时间】:2021-01-23 05:52:11
【问题描述】:

我安装了一个拦截器,它在我的 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 标头。如何更改 CONNECT User-Agent 标头?

【问题讨论】:

    标签: java okhttp interceptor fiddler


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,为什么不在authentication函数中简单地写一行:return response.request().newBuilder() .header("User-Agent", MYUSERAGENT).build();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2012-10-20
    • 2018-06-27
    • 2011-12-11
    • 2015-11-18
    • 1970-01-01
    • 2018-02-17
    相关资源
    最近更新 更多