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
相关产品推荐
相关产品推荐

