如何获取OAuth2.0访问令牌并使用此令牌使用Java客户端代码调用RESTFul Web服务?

时间:2016-08-31 11:48:08

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

我是新手编写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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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