簡體   English   中英

如何獲取OAuth2.0訪問令牌並使用此令牌通過Java客戶端代碼調用RESTFul Web服務?

[英]How to fetch OAuth2.0 Access Token and use this token to call RESTFul Web services using Java client code?

我是新來編寫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代碼執行“授權代碼”授予,但該授予類型是為真正的瀏覽器交互而設計的。 您應該查看授權類型,例如資源所有者密碼憑據或客戶端憑據,它們都可以與基於非瀏覽器的客戶端一起使用。

我無法評論Hans Z.的答案,但我認為這實際上是對隱式授予的授權請求(使用了response_type=token在此詳細介紹)。 例如,它可以是Android客戶端。 某些API在redirect_uri要求使用httphttps ,但在您的示例中缺少。 您可以試一下(也要注意百分比編碼 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM