簡體   English   中英

使用Oauth2和獨立的Java應用程序獲取訪問令牌

[英]Getting Access token using Oauth2 with standalone java application

我正在嘗試使用Google驅動器的API開發獨立的Java應用程序(僅使用Java SE)。 為此,我需要使用Oauth2.0獲取訪問令牌。為獲取訪問令牌,我編寫了以下代碼:

    package Drive;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    import static Drive.Constants.*;
    public class Test {

        public static void main(String[] args) throws IOException {

            String url=OAuth2URL+"redirect_uri=https://localhost/"+"&"+"client_id="+CLIENTID+"&"+"scope="+SCOPE+"&"+
                    "access_type=offline&"+"response_type=code";

            System.out.println("URL is :"+url);
            HttpClient httpClient= new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(url);
            HttpResponse response=httpClient.execute(httpGet);
            if(response.getEntity().getContent()!=null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String str = null;
                while ((str = reader.readLine()) != null) {
                    System.out.println(str);
                }
            }

        }
    }

我已經將我的憑據和oauth2.0 url放在了常量字符串中。我的問題是如何獲取此API調用的響應到我的應用程序中? 我是否需要在特定端口上派一個偵聽進程以獲取響應?

redirect_uri應該在Google控制台上注冊(在獲取client_id ),並且您應該將此網址公開為真實的http / s端點。

有關更多信息,請參見此處的步驟2: https : //developers.google.com/identity/protocols/OAuth2InstalledApp

暫無
暫無

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

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