我正在尝试下面的代码。控制台打印出一个 URL(粘贴到浏览器的地址栏后)将我发送到谷歌的用户同意页面并请求访问我的帐户的权限。然后它会将我重定向到我的 html 页面 - 到目前为止一切顺利。
现在,我不确定是否收到 token 或授权代码。我从哪里获取它?然后我是否必须从 Web 应用程序发送 HTTP 休息调用才能与 Gmail API 请求一起发送,或者我可以通过 JAVA 执行此操作吗?
public class People {
public void setUp() throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String clientId = "client_id";
String clientSecret = "secret";
String redirectUrl = "http://localhost:8080/TestingGmailMail/webapps/login.html";
String scope = "https://www.googleapis.com/auth/contacts.readonly";
String authorizationUrl = new GoogleBrowserClientRequestUrl(clientId,redirectUrl,Arrays.asList(scope)).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
}
}
最佳答案
是的,@DalmTo 正确地指出客户端库是应该处理所有这些的库。
更好的设计是将应用程序的用户凭据存储在目录中。
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".store/mail_credentials");
现在,为 FileDataStoreFactory
创建一个全局实例。
private static FileDataStoreFactory DATA_STORE_FACTORY;
在获取凭证之前实例化DATA_STORE_FACTORY
,最好在静态 block 中。
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
从 Google 开发者控制台下载并存储 client_secret.json
。使用以下方法获取凭据:
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in
= GmailQuickStart.class.getResourceAsStream("/client_secrets.json");
GoogleClientSecrets clientSecrets
= GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow
= new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
每当调用上述方法时,它都会在提供给 DATA_STORE_DIR
的路径中查找 StoredCredential
。如果找到,则代码按原样执行。如果没有,将打开一个浏览器,要求您登录并授权您的应用程序。这样生成的凭据将存储在 DATA_STORE_DIR
位置。只要 StoredCredential
存在,您的应用就不会请求许可。这是一种通用设计,也可用于其他 Google API。
关于Java - GMail API - 授权码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36833272/