Java Google Contacts API访问服务帐户身份验证

Java Google Contacts API访问服务帐户身份验证,第1张

Java Google Contacts API访问服务帐户身份验证

调用

setServiceAccountUser()
我的代码就可以很好地工作。但是您只会拥有一个模拟帐户(service_account_mail),而不是您的个人联系人。

“ 401未经授权”异常的另一个可能来源是遥不可及

credential.refreshToken()
。调用是将访问代码写入引用所必需的。

在完成的课程下面:

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;import com.google.api.client.http.HttpTransport;import com.google.api.client.json.jackson2.JacksonFactory;import com.google.gdata.client.contacts.ContactsService;import java.io.File;import java.io.IOException;import java.security.GeneralSecurityException;import java.util.Collections;public class Connector {  private static ContactsService contactService = null;  private static HttpTransport httpTransport;  private static final String APPLICATION_NAME = "Your-App/1.0";  private static final String SERVICE_ACCOUNT_EMAIL = "xy@developer.gserviceaccount.com";  private Connector() {    // explicit private no-args constructor  }  public static ContactsService getInstance() {    if (contactService == null) {      try {        contactService = connect();      } catch (GeneralSecurityException | IOException e) {        e.printStackTrace();      }    }    return contactService;  }  private static ContactsService connect() throws GeneralSecurityException, IOException {    httpTransport = GoogleNetHttpTransport.newTrustedTransport();    // @formatter:off    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(Collections.singleton("https://www.google.com/m8/feeds")).setServiceAccountPrivateKeyFromP12File(new File("key.p12")).build();    // @formatter:on    if (!credential.refreshToken()) {      throw new RuntimeException("Failed OAuth to refresh the token");    }    ContactsService myService = new ContactsService(APPLICATION_NAME);    myService.setOAuth2Credentials(credential);    return myService;  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5429616.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存