不调用
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; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)