Google 日历数据是私人用户数据,要在用户日历上创建偶数,您需要拥有该日历的用户的许可。
为此,我们使用称为 Oauth2 的东西,使用 Oauth2,您的应用程序将请求用户访问数据的权限,并且授权服务器将向您返回一个令牌,授予您代表用户访问 API 的权限。
如果没有所有者授予您访问权限,则无法访问私人用户数据。
无需每次使用 google api 从 UI 中获得客户端的同意
现在您可以做的一件事是请求用户的离线访问权限,如果用户授予您离线访问权限,您将获得一个刷新令牌,您可以在以后使用它来请求新的访问令牌。使用访问令牌,您可以更改用户日历,而无需他们实际运行您的应用程序。
DATA_STORE_DIR 用于用户存储
这段代码应该是关闭的,它对谷歌分析的示例进行了一些更改,但应该向您展示如何使用 DATA_STORE_DIR 来存储用户凭据以供以后使用。
/**
* A simple example of how to access the Google calendar API.
*/
public class HelloCalendar {
// Path to client_secrets.json file downloaded from the Developer's Console.
// The path is relative to HelloCalendar.java.
private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";
// The directory where the user's credentials will be stored.
private static final File DATA_STORE_DIR = new File(
System.getProperty("user.home"), ".store/hello_calendar");
private static final String APPLICATION_NAME = "Hello Calendar";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static NetHttpTransport httpTransport;
private static FileDataStoreFactory dataStoreFactory;
public static void main(String[] args) {
try {
Calendar service = initializeCalendar();
// do stuff here
printResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initializes an authorized calendar service object.
*
* @return The Calendar service object.
* @throws IOException
* @throws GeneralSecurityException
*/
private static Calendar initializeCalendar() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// Load client secrets.
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(Calendar.class
.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));
// Set up authorization code flow for all authorization scopes.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
.Builder(httpTransport, JSON_FACTORY, clientSecrets,
CalendarScopes.all()).setDataStoreFactory(dataStoreFactory)
.build();
// Authorize.
Credential credential = new AuthorizationCodeInstalledApp(flow,
new LocalServerReceiver()).authorize("THISISTHEUSERNAME");
// Construct the Analytics Reporting service object.
return new Calendar.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}