Error which i am getting:
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?
What am i doing wrong?
I'm guessing credential.getRequestInitializer() is null.
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's documentation especifies the following:
** 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} 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 Authorization: Bearer {accessToken} Host: googleapis.com**
Hope this will help you