大家好。如何正确地将请求从 curl 传输到 HttpClient 或 URL,更准确地说,我需要登录(获取令牌)
curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=password"
通过 CUrl - 一切正常,我在响应中得到一个令牌,通过 HttpClient 我在响应中得到它
{"timestamp":1518116152990,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/oauth/token"}
我按照这里的描述试过了,但可能搞砸了。
HttpClient httpClient = HttpClients.createDefault();
HttpUriRequest request1 = RequestBuilder.get("http://localhost:8080/oauth/token")
.addHeader("trusted-app", "secret")
.setEntity(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("grant_type", "password"),
new BasicNameValuePair("username", "user"),
new BasicNameValuePair("password", "password")
)))
.build();
HttpResponse response1 = httpClient.execute(request1);
Assert.assertEquals(HttpStatus.OK, response1.getStatusLine().getStatusCode());
提前感谢您的回复!
当您通过 curl 发出请求时,
trusted-app:secret
这不是 HTTP 标头,而是登录名和密码,请参阅RFC1738。curl 中的标头是这样设置的,例如:curl --header "Host: localhost" 127.0.0.1
也就是说,您在 Java 中所做的与您在 curl 中所做的不匹配。
oauth 授权的正确 CUrl 请求转换
在 HttpClient 中会是这样的
在哪里:
请参阅RFC1738规范 记住也很重要 - 仅支持 POST 请求