0

在使用 gmail 帐户成功进行身份验证后,我尝试获取用户信息(tok 是有效令牌):

        GoogleCredential credential2 = new GoogleCredential.Builder()
                .setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
                .setRequestInitializer((new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest request)
                            throws IOException {
                        request.getHeaders().setAuthorization("Bearer ".concat(tok));
                    }
                }))
                .build();

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

        Userinfo userInfo = userInfoService.userinfo().get().execute();
        logger.warn("User email: {}", userInfo.getEmail());
        logger.warn("User gender: {}", userInfo.getGender());
        logger.warn("User complet name: {} - {}", userInfo.getFamilyName(), userInfo.getName());

但日志显示所有字段为“null”,返回的 json 数据仅包含 id:

{
 "id": "113695880661351193041"
}

我该怎么办?添加一个特殊的范围来做到这一点?我尝试了几次都没有成功,只是添加了 scope= https://www.googleapis.com/auth/userinfo.profile作为 url 参数,也许这是错误的?

希望有人可以帮助或知道如何为我的请求添加范围并从该服务中获得正确的响应。

4

1 回答 1

1

这对我有用:

Credential credential = OAuth2Utils.newFlow().loadCredential(userId);

Oauth2 service = new Oauth2.Builder(OAuth2Utils.HTTP_TRANSPORT, OAuth2Utils.JSON_FACTORY, credential).setApplicationName("appname").build();

UserInfo userInfo = service.userinfo().get().execute();

这些是返回的一些属性:

  • userInfo.getBirthday()

  • userInfo.getFamilyName()

  • 用户信息.getGender()

  • userInfo.getGivenName()

  • 用户信息.getHd()

  • 用户信息.getLink()

代码中引用的实用程序类OAuth2Utils

/** Global instance of the HTTP transport. */
public final static HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

/** Global instance of the JSON factory. */
public final static com.google.api.client.json.JsonFactory JSON_FACTORY = new com.google.api.client.json.jackson2.JacksonFactory();

public static GoogleAuthorizationCodeFlow newFlow() throws IOException {
    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(),
            Arrays.asList(SCOPES)).setCredentialStore(new OAuth2CredentialStore()).setAccessType("offline")
            .setApprovalPrompt("force").build();
}
于 2013-05-25T18:31:43.407 回答