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

Apache HttpClient重复请求丢失Authorization头,401异常消失求助

解决重复HTTP请求丢失Authorization头的问题

这种情况大多是HTTP客户端默认缓存了失败的认证尝试,避免重复发送无效凭证导致的。针对不同常用客户端,解决方法如下:

Apache HttpClient

  • 全局禁用认证缓存:直接关闭客户端的AuthCache功能,强制每次请求都携带Authorization头:
CloseableHttpClient httpClient = HttpClientBuilder.create()
    .disableAuthCaching()
    .build();
  • 手动清理单次请求的缓存:如果不想全局禁用,可在每次请求前重置请求上下文的AuthCache:
// 创建空的认证缓存
AuthCache authCache = new BasicAuthCache();
HttpClientContext context = HttpClientContext.create();
context.setAuthCache(authCache);
// 携带该context执行请求,确保本次请求不受之前失败认证的缓存影响

OkHttp

  • 强制通过拦截器添加认证头:自定义拦截器,在每次请求时手动注入Authorization头,绕过客户端的自动缓存逻辑:
Interceptor authInterceptor = chain -> {
    Request originalRequest = chain.request();
    // 替换为你的实际凭证
    String credentials = Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP);
    Request authenticatedRequest = originalRequest.newBuilder()
        .header("Authorization", "Basic " + credentials)
        .build();
    return chain.proceed(authenticatedRequest);
};

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(authInterceptor)
    .build();
  • 禁用默认认证缓存逻辑:通过自定义Authenticator,不使用OkHttp的缓存机制:
OkHttpClient client = new OkHttpClient.Builder()
    .authenticator((route, response) -> {
        // 直接返回null,让请求在认证失败时直接返回401,不缓存失败状态
        return null;
    })
    .build();

Spring RestTemplate

  • 通过拦截器强制添加认证头:给RestTemplate添加请求拦截器,每次请求前注入Authorization头:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add((request, body, execution) -> {
    String credentials = Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP);
    request.getHeaders().set("Authorization", "Basic " + credentials);
    return execution.execute(request, body);
});
  • 基于HttpClient配置禁用缓存:如果RestTemplate使用HttpComponentsClientHttpRequestFactory,可参照Apache HttpClient的配置禁用AuthCache:
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
CloseableHttpClient httpClient = HttpClientBuilder.create()
    .disableAuthCaching()
    .build();
factory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);

通用思路

  1. 强制注入认证头:通过拦截器、过滤器等方式,在请求发送前手动添加Authorization字段,完全绕过客户端的自动认证管理。
  2. 关闭失败认证缓存:禁用客户端内置的失败认证缓存机制,确保每次请求都会重新发送认证信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:05:19