我找不到在 Java 中重现以下curl oAuth 身份验证调用的方法:
curl 'https://id.herokuapp.com/oauth/token' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: application/json' -H 'Authorization: Basic AUTH_VALUE' -H 'Connection: keep-alive' --data 'username=_USERNAME&password=_PASSWORD&grant_type=password&scope=read%20write&client_secret=_SECRET&client_id=_CLIENT_ID' --compressed
我不知道如何将 --data
值传递给调用。
最佳答案
如果你使用标准的java.net.URL也可以,但是语法比较麻烦,我建议你尝试使用HTTP Components library 。你最终应该得到这样的结果:
final HttpUriRequest request = RequestBuilder.get()
.setUri("https://id.herokuapp.com/oauth/token")
.setHeader("Content-Type", "application/x-www-form-urlencoded")
.setHeader("Accept", "application/json")
.setHeader("Authorization", "Basic AUTH_VALUE")
.addParameter("username", "_USERNAME")
.addParameter("password", "_PASSWORD")
.addParameter("grant_type", "password")
.addParameter("scope", "read write")
.addParameter("client_secret", "_SECRET")
.addParameter("client_id", "_CLIENT_ID")
.build();
final HttpClient client = HttpClientBuilder.create().build();
final HttpResponse response = client.execute(request);
final HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity)); // or whatever processing you need
如果使用 HttpClientBuilder 创建 HttpClient,则开箱即用地提供 GZip/deflate 和保持 Activity 处理。
关于java - Java 中的 Curl oAuth 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26850118/