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

OkHttpClient携带Bearer Token发送GET请求返回401问题排查

OkHttpClient 4.9.2发送Authorization头返回401的排查与解决

首先看你提供的代码,存在语法错误:Request.Builder()后面多了一个分号,导致后续的.url()、.header()调用属于无效的链式调用,最终构建的Request对象根本没有设置Authorization头,这大概率是导致401的直接原因。

第一步:修正代码语法错误

正确的代码应该移除Request.Builder()后的分号:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url(url)
        .header("Authorization", "Bearer " + token)
        .build();

Response response = client.newCall(request).execute();

其他可能的原因及解决方法

如果修正语法后问题依旧,按以下顺序排查:

1. 验证Token本身的有效性

直接用curl或Postman发送相同请求,确认Token是否能通过认证:

curl -H "Authorization: Bearer YOUR_TOKEN" YOUR_REQUEST_URL

如果返回仍然是401,说明Token存在过期、格式错误(比如服务器要求的认证前缀不是Bearer)或权限不足等问题,和OkHttpClient无关。

2. 检查拦截器是否修改/移除了请求头

如果你的OkHttpClient添加了自定义拦截器或日志拦截器,可能会无意中修改Authorization头。暂时移除所有拦截器,测试请求是否正常。

如果需要保留拦截器,可添加日志拦截器查看实际发送的请求头,确认Authorization是否存在:

// 添加日志拦截器依赖(Maven)
// <dependency>
//     <groupId>com.squareup.okhttp3</groupId>
//     <artifactId>logging-interceptor</artifactId>
//     <version>4.9.2</version>
// </dependency>

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)
        .build();

运行后查看控制台输出,确认请求头中是否包含Authorization字段。

3. 处理重定向导致的头丢失

OkHttpClient默认会在跨域重定向时移除Authorization头。如果你的请求存在重定向,可通过自定义重定向策略保留头:

OkHttpClient client = new OkHttpClient.Builder()
        .redirectPolicy(new RedirectPolicy() {
            @Override
            public boolean follow(Request request, Response response, Route route) {
                return RedirectPolicy.DEFAULT.follow(request, response, route);
            }

            @Override
            public Request followRequest(Request userRequest, Response response, Route route) {
                // 保留原请求的Authorization头
                return RedirectPolicy.DEFAULT.followRequest(userRequest, response, route)
                        .newBuilder()
                        .header("Authorization", userRequest.header("Authorization"))
                        .build();
            }
        })
        .build();

或者直接禁用重定向,手动处理跳转逻辑:

OkHttpClient client = new OkHttpClient.Builder()
        .followRedirects(false)
        .build();

内容的提问来源于stack exchange,提问作者eldar.j

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:21:57