我想連接到谷歌聯繫人api來訪問我的聯繫人/保存在谷歌的人,但它會拋出TokenResponseException:401未授權。我對Google Oauth2.0有點新穎。我已經根據需要將服務帳戶密鑰文件下載到我的項目根目錄。TokenResponseException:401未授權當試圖訪問谷歌聯繫人Api
下面是代碼:
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.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
public class Connector {
private static ContactsService contactService = null;
private static HttpTransport httpTransport;
private static final String APPLICATION_NAME = "example";
private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]";
private static final java.util.List<String> SCOPE = Arrays.asList("https://www.google.com/m8/feeds/");
private Connector() {
// explicit private no-args constructor
}
public static void main(String[] args) {
System.out.println(getInstance());
}
public static ContactsService getInstance() {
if (contactService == null) {
try {
contactService = connect();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return contactService;
}
private static ContactsService connect() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
java.io.File p12File = new java.io.File("example-e8135faedf4e.p12");
// @formatter:off
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPE)
.setServiceAccountPrivateKeyFromP12File(p12File)
.setServiceAccountUser("[email protected]")
.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;
}
}
但是以下異常被拋出:
com.google.api.client.auth.oauth2.TokenResponseException:401未經授權
空
com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105) at com.google.api.client.auth.oauth2.TokenRequest.executeU nparsed(TokenRequest.java:287) at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307) at com.google.api.client.googleapis.auth.oauth2。 GoogleCredential.executeRefreshToken(GoogleCredential.java:384) 在 com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489) 在Connector.connect(Connector.java:58)在 連接器.getInstance(Connector.java:31)在 Connector.main(Connector.java:25)BUILD SUCCESSFUL(總時間:9秒 )
我看到這麼晚了,但感謝您的幫助。我能夠解決這個問題,讓我馬上發佈最終代碼 –
@MichaelGatumaSelvatico:你的解決方案是什麼。 –