java - Java 中的 Curl oAuth 等效项

标签 java curl heroku oauth

我找不到在 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/

相关文章:

linux - 使用 curl 将文件上传到 owncloud

bash - 为 http 响应中的每一行添加换行符

Java Spring boot 2.0.5 MultipartFile上传 "Content type not supported"

java.sequence处理运算符?

java - 使用基本枚举作为依赖枚举的默认值

android - 在安卓中 curl

ruby-on-rails - 更新 Heroku 生产数据库中的字符串属性

javascript - WS : path is undefined

ruby-on-rails - Rails 本地主机不工作

java - 通过 GET 方法重定向到 j_spring_security_check