尝试使用OAuth2对java客户端库(gData 1.47.1)进行身份验证并进行一次调用时,我收到异常。以下是例外情况:
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.<init>(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:645)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at com.test.Main.main(Main.java:79)
创建服务的代码:
String scope = "https://www.google.com/m8/feeds";
ContactsService service = new ContactsService("APP_NAME");
service.setOAuth2Credentials(getCredential(scope, userEmail));
public GoogleCredential getCredential(ArrayList<String> scopes, String userEmail) throws Exception {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(this.serviceAccountEmail).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(f)
.setServiceAccountUser(userEmail).build();
return credential;
}
致电:
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
我还在我的应用程序控制台中为该项目启用了Contacts API,如文档中所述。任何建议将不胜感激。谢谢。
答案 0 :(得分:0)
同样的事发生在我身上。我通过在令牌到期时刷新令牌来修复它。
if (credential != null && (credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() < 5)) {
credential.refreshToken();
}
IMO,较新的google-api-client-java会自动执行此操作,而Gdata则不会这样做。