You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用带身份验证的Proxy发起OkHttp请求失败

解决OkHttp代理认证请求失败的问题

首先看你的代码,authenticate方法里的返回语句没写完,这大概率是请求失败的核心原因。我给你补全并优化这段代码,同时说明关键注意事项:

final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhost", 8001));
OkHttpClient client = new OkHttpClient.Builder()
    .proxy(proxy)
    .proxyAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // 避免无限重试:如果已经尝试过认证仍失败,直接返回null终止请求
            if (response.request().header("Proxy-Authorization") != null) {
                return null; // 认证失败,放弃重试
            }
            String credential = Credentials.basic("proxyuser", "proxypass");
            // 给原请求添加代理认证专属的请求头
            return response.request().newBuilder()
                .header("Proxy-Authorization", credential)
                .build();
        }
    })
    .build();

// 发起请求示例
try {
    Request request = new Request.Builder()
        .url("https://your-target-url.com")
        .build();
    Response response = client.newCall(request).execute();
    // 处理响应逻辑
    response.close();
} catch (IOException e) {
    e.printStackTrace();
}

关键注意事项:

  • 用对请求头:代理认证需要用Proxy-Authorization头,而非普通的Authorization(后者是给目标服务器的认证),这是很多人容易踩的坑。
  • 防无限循环:必须判断是否已经添加过认证头,若重试后仍失败就返回null,否则OkHttp会一直重复发起认证请求。
  • 校验基础信息:确认proxyhost、8001端口是有效的代理地址,proxyuser和proxypass能通过代理服务器的身份验证。
  • 排查拦截器影响:如果你的OkHttpClient还配置了其他拦截器,要确保它们没有意外移除或修改Proxy-Authorization头。

如果修改后还是失败,建议抓包查看请求头,确认Proxy-Authorization是否正确发送到了代理服务器。

内容的提问来源于stack exchange,提问作者Aleksey Khokhrin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:27:16