Java:Google+ OAuth header 无效

标签 java oauth google-plus

我正在尝试使用以下方式获取 Google+ 用户的信息

https://www.googleapis.com/oauth2/v1/userinfo?alt=json

我传递我之前获得的访问 token :

URL googleURL = new URL("https://www.googleapis.com/oauth2/v1/userinfo?alt=json");

            URLConnection googleConn = googleURL.openConnection();
            googleConn.setAllowUserInteraction(false);   
            googleConn.setDoOutput(true);

            **googleConn.setRequestProperty("Authorization", "Bearer "+accessToken);**

            BufferedReader rd = new BufferedReader(new InputStreamReader(googleConn.getInputStream()));

            String result = "";
            while(rd.ready())
                result += rd.readLine();
            rd.close();

但它给了我 HTTP 错误代码 401(无效 header )。

这是在 header 中传递访问 token 的正确方法吗?

googleConn.setRequestProperty("Authorization", "Bearer "+accessToken);

最佳答案

要访问 Google+ 个人资料信息,您实际上需要使用 people get API:https://www.googleapis.com/plus/v1/people/me您可能想查看 reference docs或在 API Explorer 中使用它.

此外,您的编码水平比您需要的水平低得多。虽然您可以直接使用 REST 端点,但如果您使用 official client library,事情会容易得多。 .如果你走这条路,甚至会有一个 Google+ starter project for Java .

如果您想继续低级别,您应该使用 OAuth 前缀而不是 Bearer 传递访问 token 。您生成的 HTTP 请求 header 将如下所示:

GET https://www.googleapis.com/plus/v1/people/102817283354809142195

Authorization:  OAuth ya29.BHES61Rxr4Cq-Elcfpvx_2oWC443fMOEQV9iS5-M7ZjJ6xk

关于Java:Google+ OAuth header 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9109035/

相关文章:

java - 如何通过 Java Http Post 发送和接受文件?

java - 捕获 OutOfMemoryError 但不增加堆大小

java - 编译 Java 8 中的一个奇怪的 NullPointerException(编译器(1.8.0_31))

azure - 为什么我的 Azure 网站不接受 OAuth token ?

google-plus - 如何在 Google+ 中为我的页面设置短网址或用户名

android - java.lang.NullPointerException 与 Google +1 按钮集成

android - "code": 403, 和 "reason": "forbidden"在 google plus 中上传文件时出现异常

java - 如何使从 Java Runtime.exec(command) 打开的程序始终在最前面

java - Spring Boot 2 Oauth 无限重定向

oauth - openid、oauth 1.0、oauth1.0a、oauth 2.0 和 open id connect 之间有什么区别?