通过 OAuth 2.0 服务帐户调用 Google Contacts API 会给出 AuthenticationEx



这是我一直在处理的代码:

public String getGoogleContact(String queryStr) throws
    AuthenticationException, MalformedURLException, IOException,
    ServiceException, GeneralSecurityException{
        String emailAddress = "something@developer.gserviceaccount.com";
        JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        String path = "src/main/resources/key.p12";
        GoogleCredential credential = new GoogleCredential.Builder()
                                    .setTransport(httpTransport)
                                    .setJsonFactory(JSON_FACTORY)
                                    .setServiceAccountId(emailAddress)
                                    .setServiceAccountPrivateKeyFromP12File(new java.io.File(path))
                                    .setServiceAccountScopes(Collections.singleton("https://www.google.com/m8/feeds"))
                                    .setServiceAccountUser("myEmail@example.com").build();
        ContactsService service = new ContactsService("MYAPP");
        service.setOAuth2Credentials(credential);
        Query myQuery = new Query( new URL("https://www.google.com/m8/feeds/contacts/default/full"));
        myQuery.setFullTextQuery(queryStr);
        ContactFeed resultFeed = service.query(myQuery, ContactFeed.class);
        String result = "";
       for (ContactEntry entry : resultFeed.getEntries()) {
           result += entry.getTitle().getPlainText();
       }
       return result;
    }

我得到以下异常:

java.lang.NullPointerException: 无身份验证标头信息 at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96) ~[core-1.47.1.jar:na] at com.google.gdata.util.AuthenticationException.(身份验证异常.java:67) ~[core-1.47.1.jar:na] at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608) ~[core-1.47.1.jar:na] at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564) ~[core-1.47.1.jar:na] at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560) ~[core-1.47.1.jar:na] at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538) ~[core-1.47.1.jar:na] at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536) ~[core-1.47.1.jar:na] at com.google.gdata.client.Service.getFeed(Service.java:1135) ~[core-1.47.1.jar:na] at com.google.gdata.client.Service.getFeed(Service.java:1077) ~[core-1.47.1.jar:na] at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676) ~[core-1.47.1.jar:na] at com.google.gdata.client.Service.query(Service.java:1237) ~[core-1.47.1.jar:na] at com.google.gdata.client.Service.query(Service.java:1178) ~[core-1.47.1.jar:na]

请帮忙!

将此解决方法添加到联系人服务初始化块

service.getRequestFactory().setHeader("User-Agent", applicationName);

最新更新