繁体   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