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

Apache HttpPost中grant_type设置问题:401未授权错误排查

问题分析与修复

你的grant_type设置方式是正确的,返回401 Unauthorized的核心问题出在授权头配置,还有几个潜在细节需要修正:

1. 核心错误:Authorization头名称错误

你代码里的授权头写的是:

httpPost.setHeader("HttpHeaders.AUTHORIZATION", "Basic "+base64encoded);

这里的头名应该直接用Authorization,HttpHeaders.AUTHORIZATION是框架常量(比如Spring),它的实际值才是Authorization,直接写常量字符串会导致服务端无法识别授权信息,返回401。

2. 其他潜在问题

  • 请求URL不匹配:Java代码里用的是http://example.com,但curl请求的是https://dev1.erf.us-phoenix-1.ocs.oc-test.com/ords/erfp/oauth/token,必须保证两者一致。
  • Base64编码验证:确认base64encoded是clientId:clientSecret的标准Base64编码,没有多余空格或编码错误。

修正后的完整代码

List<NameValuePair> postParameters = new ArrayList<>();
// 替换为curl里的真实请求URL
HttpPost httpPost = new HttpPost("https://dev1.erf.us-phoenix-1.ocs.oc-test.com/ords/erfp/oauth/token");
postParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, StandardCharsets.UTF_8));
// 修正授权头名称
httpPost.setHeader("Authorization", "Basic " + base64encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

tokenApiResponse = this.httpClient.execute(httpPost);
LOGGER.log(Level.INFO,"Token response:{0}",tokenApiResponse.getStatusLine().getStatusCode());

如果需要生成正确的Base64编码,可参考这段逻辑:

String credentials = "你的clientId:你的clientSecret";
String base64encoded = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:19:54