java - 如何像在 Google Oauth Playground 中一样向 Google API 发送 HTTP 请求?

标签 java http https google-oauth

我在这里尝试了 google oauth Playground : https://developers.google.com/oauthplayground/


第 1 步,我选择日历 API v3,然后请求权限 -> 我选择我的谷歌帐户并单击“允许”

第二步,我点击了“兑换代币授权码”

第 3 步,我输入“https://www.googleapis.com/calendar/v3/calendars/primary/events”(选择列出我拥有的所有事件),然后单击“发送请求”-> 输出是 HTTP 响应,其中包含我的主日历中的事件列表,格式为 json


我的问题是: 我可以像这样通过 HTTP 请求-响应使用 Google API(尤其是日历)吗?

基本上我想发出 playground 中所示的 HTTP 请求,并获得 playground 中所示的 HTTP 响应

(例如:使用java socket编程如下)

        String httpsURL = "https://accounts.google.com/o/oauth2/token";

        String query = "code="+("123123123123codehere"); 
        query += "&client_id="+("123123123123.apps.googleusercontent.com");
        query += "&client_secret="+("123123123123");
        query += "&redirect_uri="+("urn:ietf:wg:oauth:2.0:oob");
        query += "&grant_type="+("authorization_code");

        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-length", String.valueOf(query.length())); 

        con.setDoOutput(true); 
        con.setDoInput(true); 

        DataOutputStream output = new DataOutputStream(con.getOutputStream());  

        output.writeBytes(query);
        output.close();
        DataInputStream input = new DataInputStream( con.getInputStream() ); 

        for( int c = input.read(); c != -1; c = input.read() ) 
        System.out.print( (char)c ); 
        input.close(); 

        System.out.println("Resp Code:"+con .getResponseCode()); 
        System.out.println("Resp Message:"+ con .getResponseMessage());

这些代码不起作用,输出为空白(为什么?字符串 httpRequest 被复制粘贴到与 oauth playground 完全相同的位置,并且 token 尚未过期)

我也打算用curl在php中使用这些,可以吗?

最佳答案

日历 API 等 Google API 只是 rest APIs这意味着它们通过 HTTP GET 和 HTTP Post 请求运行。

您可以轻松地发送原始的 http 帖子并进入 google 并获得您的回复。

您获得的访问 token 将在一小时后过期。刷新 token 不会过期,并在过期时用于获取新的访问 token 。我有一个关于 Google 3 legged oauth2 flow 的教程

您可能要考虑使用 Google Java client library虽然它会更容易。

关于java - 如何像在 Google Oauth Playground 中一样向 Google API 发送 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640148/

相关文章:

java - Libgdx - 使一个实体部分免受物理影响

java - 在 JBoss esb 服务器中找不到我的 bean

java - 将通用列表转换为数组。为什么我需要使用克隆?

http - golang 服务器不解码 json(文字 false 中的无效字符 ' '(预期 'a')400")

node.js - 在 ondata 事件中更改 node.js 流

azure - 为什么此 Azure 网站“仅有时”无法显示中间 SSL 证书?

java - JAVA中数组的值未经操作就改变了

node.js - 使用 Claudia-Api-Builder 为 AWS ApiGateway 设置 HTTP 选项响应

javascript - 如何实现由第三方服务器触发的JavaScript方法?

security - 确保页面安全的干净/简单的方法是什么?