Home » Java » How to get list of the user's albums using new Google Photos API

How to get list of the user's albums using new Google Photos API

Posted by: admin June 30, 2018 Leave a comment

Questions:

I want to get list of my albums from Google Photos.
And I’m using new REST API.

I wrote the code which executes GET request:

GET
https://photoslibrary.googleapis.com/v1/albums

according to the official guide: https://developers.google.com/photos/library/guides/list
And this code only returns response with status 200, but without json body:

Listing:

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);
}

Also i tried to use other REST clients (e.g. Postman) and the same result i recieve is:

{}
Answers: