简体   繁体   中英

Curl oAuth equivalent in Java

I can't find the way to reproduce the following curl oAuth authentication call in Java:

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

I don't know how to pass the --data value to the call.

If you're using standard java.net.URL it can be done but the syntax is rather cumbersome, I suggest that you try using HTTP Components library . You should end up with something like this:

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

GZip/deflate and keep alive handling is provided out of the box if the HttpClient is created using HttpClientBuilder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM