我正在开发一个访问谷歌获取权限之后操作谷歌邮箱API的功能,现在在访问谷歌获取访问令牌出现问题
以下是我的开发代码:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import java.io.*;
import java.net.URISyntaxException;
import java.security.*;
import java.util.Arrays;
import java.util.Collections;
public class GoogleApiAuthUtil {
/** Email of the Service Account */
private static final String SERVICE_ACCOUNT_EMAIL = "xxxxx@testproject-355611.iam.gserviceaccount.com";
/** Path to the Service Account's Private Key file */
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "p12key.p12";
/**
* Build and returns a Directory service object authorized with the service accounts
* that act on behalf of the given user.
*
* @param userEmail The email of the user. Needs permissions to access the Admin APIs.
* @return Directory service object that is ready to make requests.
*/
public static Directory getDirectoryService(String userEmail) throws GeneralSecurityException,
IOException, URISyntaxException {
FileInputStream inputStream = new FileInputStream(file);
HttpTransport httpTransport = new NetHttpTransport();
GsonFactory jsonFactory = new GsonFactory();
GsonFactory defaultInstance = GsonFactory.getDefaultInstance();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(DirectoryScopes.ADMIN_DIRECTORY_USER))
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Directory directory = new Directory.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return directory;
}
}
以下是运行结果:
[2022-07-28 16:38:12.616 employee-account ERROR ,, http-nio-8090-exec-2 com.employeeaccount.common.tool.exceptio n.GlobalExceptionHandler java.lang.IllegalArgumentException
com.google.common.base.Preconditions.checkArgument(Preconditions.java:131)
com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:35)
com.google.api.client.googleapis.auth.oauth2.GoogleCredential. (GoogleCredential.java:317)
com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.build(GoogleCredential.java:516)
com.shareit.employeeaccount.common.utils.email.GoogleApiAuthUtil.getDirectoryService(GoogleApiAuthUtil.java:74)
com.shareit.employeeaccount.controller.email.EmailController.test(EmailController.java:197)
我尝试了很多方法,通过查询得知应该是 GoogleCredential.build 的时候参数构建问题,但是还是无法解决,希望来个能人指点一下迷津。
直接将对象new出来,然后再set参数
GoogleCredential credential = new GoogleCredential();
credential .setTransport(httpTransport);