Java POST 请求从网络服务获取令牌

Java POST request to get token from web service

我需要从 java 应用程序访问某些使用 token-based 身份验证的 RESTful Web 服务。据我了解,为此目的的最佳选择是使用像 Jersey 这样的 JAX-RS-based 库,但我对这件事很陌生。也许有人可以通过提供正确请求的示例代码来帮助我从 Web 服务获取令牌。

我们有:

据我了解,要获得令牌,我必须发送 POST 请求以及以下 headers:

和以下参数:

grant_type=password&username=someusername&password=somepassword&scope=profile

希望有人能帮助我编写示例代码。

几点:

  • URL 您指定的请求属于 Resource Owner Password Credentials Grant。确保您处于此补助金适用的场景中(更多详细信息 here)。
  • JAX-RS 是关于实现 REST api,而不是关于客户端调用(也许你在谈论“jax-rs 客户端”?如果是这样的话,就 oauth 而言,它属于我的最后一个与任何其他 http 客户端一样点类别)。
  • 有些库可以为您处理获取访问令牌,因此您只需提供属性并决定如何处理生成的令牌。例如,如果您可以使用 spring、Spring Security OAuth2(仅讨论“客户端角色”配置;您将使用外部授权服务器) .
  • 如果这些库不适合您的情况:您只需要 implement/use 一个 http 客户端来对该授权服务器进行标准调用(它们只是 REST api)。一些选项:apache httpcomponentsSpring RestTemplatejdk HttpUrlConnection

已解决!

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public void getHttpCon() throws Exception{

    String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
    URL obj = new URL("http://someIP/oauth/token");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json;odata=verbose");
    con.setRequestProperty("Authorization",
            "Basic Base64_encoded_clientId:clientSecret");
    con.setRequestProperty("Accept",
            "application/x-www-form-urlencoded");

    // For POST only - START
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(POST_PARAMS.getBytes());
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { //success
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
    } else {
        System.out.println("POST request not worked");
    }
}