【问题标题】:How to fetch OAuth2.0 Access Token and use this token to call RESTFul Web services using Java client code?如何获取 OAuth2.0 访问令牌并使用此令牌使用 Java 客户端代码调用 RESTFul Web 服务?
【发布时间】:2023-03-23 04:40:01
【问题描述】:

我是编写 Java 客户端代码来调用 RestFul Web 服务的新手。这些 Web 服务使用 OAuth2.0 安全性。我有客户端 ID 和密钥,但无法通过 Java 程序调用。我应该如何从中获取访问令牌并将此令牌进一步用于 Web 服务 API 调用。以下是我的尝试:

private static void authorizationProcess() throws ClientProtocolException, IOException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpContext context = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("https://www.ustream.tv/oauth2/authorize?response_type=token&client_id=671c71f800c17f1d57f10eebeba2f42d230143cddji8&redirect_uri=www.ustream.tv");
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet, context);
        System.out.println("Response status: " + httpResponse.getStatusLine());
        HttpRequest req = (HttpRequest) context.getAttribute(
                ExecutionContext.HTTP_REQUEST);
        System.out.println("Last request URI: " + req.getRequestLine());
        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
                DefaultRedirectStrategy.REDIRECT_LOCATIONS);
        if (redirectLocations != null) {
            System.out.println("All intermediate redirects: " + redirectLocations.getAll());
        }
        EntityUtils.consume(httpResponse.getEntity());
    } finally {
        httpGet.releaseConnection();
    }
}
}

它给出了错误的请求错误消息:

Response status: HTTP/1.1 400 Bad Request
Last request URI: GET /oauth2/authorize?response_type=token&client_id=671c71f800c17f1d57f10eebeba2f42d230143cddji8&    redirect_uri=www.ustream.tv HTTP/1.1

【问题讨论】:

    标签: java web-services rest oauth-2.0 java-client


    【解决方案1】:

    您正在尝试在 Java 代码中执行授权代码授权,但该授权类型是为真正的浏览器交互而设计的。您应该查看授权类型,例如资源所有者密码凭据或客户端凭据,它们都可以用于非基于浏览器的客户端。

    【讨论】:

    • 是的,你是对的。我尝试将授权类型作为客户端凭据,现在它可以从独立的 java 应用程序中正常工作。
    【解决方案2】:

    我无法对 Hans Z. 的答案发表评论,但我认为这实际上是对隐式授权的授权请求(使用response_type=token,详细信息here)。例如,它可能是 Android 客户端。某些 API 需要 redirect_uri 中的 httphttps,这在您的示例中是缺失的。你可以试一试(请记住Percent-encoding)..

    【讨论】:

    • 感谢您的回复。现在我可以从一个独立的 Java 应用程序编写和执行客户端代码了。
    猜你喜欢
    • 2022-06-21
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多