从 Oauth2 Google Contacts API 获取用户信息 [英] Get Userinfo from Oauth2 Google Contacts API

查看:23
本文介绍了从 Oauth2 Google Contacts API 获取用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的错误:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "location" : "Authorization",
    "locationType" : "header",
    "message" : "Invalid Credentials",
    "reason" : "authError"
  } ],
  "message" : "Invalid Credentials"
}

下面的代码,我正在使用:

Below code, i am using:

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(this.TRANSPORT).setJsonFactory(this.JSON_FACTORY)
    .setClientSecrets(Constants.CLIENT_ID, Constants.CLIENT_SECRET).build();
credential.setAccessToken(tokenResponse.getAccessToken());
credential.setAccessToken(tokenResponse.getRefreshToken());

到这里,我得到了刷新令牌、访问令牌等

Till here, i get Refresh token, Access Token, etc

Oauth2 userInfoService = new Oauth2.Builder(this.TRANSPORT,
        this.JSON_FACTORY, credential.getRequestInitializer())
        .setApplicationName(Constants.APPLICATION_NAME).build();

它在以下行失败:(不知道,为什么?)

It fails at below line: (Dont know, Why?)

Userinfo userInfo = userInfoService.userinfo().get().execute();

我在网上搜索,我得到的例子和稀有材料很少.任何机构对此有任何想法?

I searched on web, and i get very less examples of it and rare materials. Any body has any idea on it?

我做错了什么?

推荐答案

我猜 credential.getRequestInitializer() 为空.

我已经通过为这样的凭证对象设置自定义请求初始值设定项来解决这个问题

I've solved this by setting an custom request initializer to the credential object like this

GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(this.TRANSPORT).setJsonFactory(this.JSON_FACTORY)
.setClientSecrets(Constants.CLIENT_ID, Constants.CLIENT_SECRET).setRequestInitializer((new HttpRequestInitializer(){
                @Override
                public void initialize(HttpRequest request)
                        throws IOException {
                    request.getHeaders().put("Authorization", "Bearer " + accessToken);
                }
            })).build()

Google 的文档规定了以下内容:

Google's documentation especifies the following:

**例如,使用 access_token 查询字符串参数调用 UserInfo API 如下所示:

** For example, a call to the UserInfo API using the access_token query string parameter looks like the following:

GET https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}使用 HTTP 标头中的访问令牌对同一 API 的调用如下所示:

GET https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken} A call to the same API using the access token in the HTTP header looks like the following:

GET/oauth2/v1/userinfo HTTP/1.1授权:承载 {accessToken}主机:googleapis.com**

GET /oauth2/v1/userinfo HTTP/1.1 Authorization: Bearer {accessToken} Host: googleapis.com**

希望对你有帮助

这篇关于从 Oauth2 Google Contacts API 获取用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆