我想从Google相册中获取相册列表。 我正在使用新的REST API。
我编写了执行GET请求的代码:
GET
https://photoslibrary.googleapis.com/v1/albums
根据官方指南:https://developers.google.com/photos/library/guides/list
并且此代码仅返回状态为200的响应,但没有json正文:
清单:
public static void main(String[] args) throws IOException, GeneralSecurityException, ServiceException, ParseException {
GoogleCredential credential = createCredential();
if (!credential.refreshToken()) {
throw new RuntimeException("Failed OAuth to refresh the token");
}
System.out.println(credential.getAccessToken());
doGetRequest(credential.getAccessToken(), "https://photoslibrary.googleapis.com/v1/albums");
}
private static GoogleCredential createCredential() {
try {
return new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAccount)
.setServiceAccountPrivateKeyFromP12File(ENCRYPTED_FILE)
.setServiceAccountScopes(SCOPE)
.setServiceAccountUser(emailAccount)
.build();
} catch (Exception e) {
throw new RuntimeException("Error while creating Google credential");
}
}
private static void doGetRequest(String accessToken, String url) throws IOException, ParseException {
logger.debug("doGetRequest, with params: url: {}, access token: {}", accessToken, url);
HttpGet get = new HttpGet(url);
get.addHeader("Authorization",
"Bearer" + " " + accessToken);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(get);
String json = EntityUtils.toString(response.getEntity());
System.out.println(json);
}
此外,我尝试使用其他REST客户端(例如Postman),我收到的结果是:
{}
答案 0 :(得分:3)
您似乎正在使用服务帐户访问API。 Google相册库API不支持Service accounts。
您需要按照here所述为 Web应用程序设置OAuth 2.0:
然后,您将使用此页面上返回的client Id
和client secret
作为请求的一部分。如果您需要离线访问,这意味着当用户不在浏览器中时进行访问,您还可以请求offline
access_type
并使用refresh tokens
来维护访问权限。
您似乎正在使用Google API Java客户端,该客户端也支持此流程。通过调用setClientSecrets(..)
来设置构建器上的客户端机密:
return new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
您还需要在应用程序中处理来自OAuth请求的回调,您将在开发人员控制台中配置的回调网址中接收访问令牌。
documentation for the client library还有一个更完整的例子。