java - 使用 Oauth2 和独立 java 应用程序获取访问 token

标签 java google-drive-api google-oauth google-drive-android-api apache-commons-httpclient

我正在尝试使用Google Drive的API来开发独立的java应用程序(仅使用java SE)。为此,我需要使用 Oauth2.0 获取访问 token 。为了获取访问 token ,我编写了以下代码:

    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 调用的响应吗?我需要 fork 吗 特定端口上的监听进程以获得响应?

最佳答案

redirect_uri 应在 Google 控制台上注册(在您获取 client_id 的地方),并且您应将此网址公开为真正的 http/s 端点。

有关详细信息,请参阅此处的步骤 2:https://developers.google.com/identity/protocols/OAuth2InstalledApp

关于java - 使用 Oauth2 和独立 java 应用程序获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47489252/

相关文章:

go - 访问 token 在 GO 中过期时如何使用谷歌刷新 token ?

java - log4j:文件已创建但未写入

java - 让我的 ActionForward 识别不同的提交按钮 - 通过 Struts Java 和 JSP

java - 监控流程输出及其执行的最佳方法

Android - Google Drive REST API - 向 CSV 文件添加一行

google-drive-api - 在 PHP 网络应用程序中使用 Google Picker 访问共享的 Google Drive

java - 将模式恢复为 CheckBox 的 ArrayList?

android - 获取可与服务器共享的 OAuth2 授权码

meteor - 如何使用 Meteor.loginWithGoogle 获取 Google+ 个人资料?

asp.net-mvc - 来自 google 控制台的动态重定向 url - oAuth