[英]HTTP Status - 401 Unauthorized
I'm trying to convert from curl to java code with intention to call an API to create a token but I get a 401 response.我正在尝试从 curl 转换为 java 代码,意图调用 API 来创建令牌,但我得到 401 响应。
Curl code: Curl 代码:
curl -X POST \
https://apigw.dev/commercial/oauth/create-token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id=dfdfdfdfd&client_secret=dfdfdf&grant_type=client_credentials'
And here my java code:这里是我的 java 代码:
@RestController
public class TokenController {
@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
public ClientCredentialsResourceDetails getAccessToken(ClientCredentialsResourceDetails resource) throws Exception {
resource.setAccessTokenUri(tokenUri);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setGrantType("client_credentials");
resource.setClientAuthenticationScheme(AuthenticationScheme.header);
resource.setScope(Arrays.asList("read", "write"));
System.out.println(resource);
return resource;
}
}
and here the results:结果如下:
"timestamp": "2020-04-28T14:02:28.381+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/getAccessToken"
}
I really appreciate your suggestion, Thanks in advance.非常感谢您的建议,在此先感谢。
You're making a POST request with CURL, but your rest controller is configured as GET.您正在使用 CURL 发出 POST 请求,但您的 rest controller 配置为 GET。 I guess you have another endpoint to /getAccessToken with POST method wich requires the token.
我猜你有另一个使用 POST 方法的 /getAccessToken 端点需要令牌。 Also, by default, every mehod in a
@RestController
class will consume an application/json
and produce an application/json
.此外,默认情况下,
@RestController
class 中的每个方法都将使用application/json
并生成application/json
。 If your request is a Content-Type: application/x-www-form-urlencoded
, change the consume type of your request to MediaType.APPLICATION_FORM_URLENCODED_VALUE
.如果您的请求是
Content-Type: application/x-www-form-urlencoded
,请将请求的使用类型更改为MediaType.APPLICATION_FORM_URLENCODED_VALUE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.