Google 提供了中文地址
https://developers.google.com/api-client-library/java?hl=zh-cn
适用于 Java 的 Google API 客户端库提供所有 Google API 通用的功能,例如 HTTP 传输、错误处理、身份验证、JSON 解析、媒体下载/上传和批处理。该库包含一个强大的 OAuth 2.0 库,它具有一致的界面;轻量级且高效的 XML 和 JSON 数据模型(支持任何数据架构);以及对协议缓冲区的支持。
要使用 Google 的 Java 版客户端库调用 Google API,您需要为要访问的 Google API 生成 Java 库。这些生成的库包含核心 google-api-java-client 库以及特定于 API 的信息(如根网址)。这些 API 还包含在 API 上下文中表示实体且有助于在 JSON 对象和 Java 对象之间进行转换的类。
调用 Google API 非常简单
您可以通过适用于 Java 的 Google API 客户端库,使用 Google 服务生成的库来调用 Google API。(如需查找为 Google API 生成的客户端库,请访问支持的 Google API 列表)。以下示例使用 Java 版日历 API 客户端库调用 Google 日历 API:
// Show events on user's calendar.
View.header("Show Calendars");
CalendarList feed = client.calendarList().list().execute();
View.display(feed);
此库简化了身份验证
该库包含一个强大的身份验证库,可以减少您需要处理 OAuth 2.0 的代码量。有时,只需几行即可。例如:
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
该库在 Google App Engine 上运行
App Engine 专属帮助程序可以快速完成对 API 的经过身份验证的调用,而您无需担心如何交换代码来换取令牌。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
AppIdentityCredential credential =
new AppIdentityCredential(Arrays.asList(UrlshortenerScopes.URLSHORTENER));
Urlshortener shortener =
new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential)
.build();
UrlHistory history = shortener.URL().list().execute();
...
}
安装简单
如果您不使用生成的库,可以直接从下载页面下载适用于 Java 的 Google API 客户端库的二进制文件,也可以使用 Maven 或 Gradle。如需使用 Maven,请将以下行添加到您的 pom.xml 文件中:
<project>
<dependencies>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.32.1</version>
</dependency>
</dependencies>
</project>
如需使用 Gradle,请将以下行添加到 build.gradle 文件中:
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.api-client:google-api-client:1.32.1'
}
参 考
https://blog.csdn.net/D1237890/article/details/150698601
https://blog.csdn.net/D1237890/article/details/151161867