Using Java blogger API v3 to post on blog dynamica

2019-04-13 17:42发布

问题:

I have two issues regarding using Java blogger API v3 to dynamically posting posts to my blogger account.

First

I used the following code to get credential for accessing my blog:

GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)                
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(emailAddress)
                .setServiceAccountPrivateKeyFromP12File(
                new File(p12FileLocation))
                .setServiceAccountScopes(Collections.singleton(BloggerScopes.BLOGGER))
                .build();

        credential.setAccessToken("zRLqmkM82626Uym9Uv1Jsdd");


        Blogger blogger = new Blogger.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName("Blogger")
                .build();
        // .... rest of the code to prepare post and send it ......

I set the access token above (credential.setAccessToken) that was generated from the following google page: https://developers.google.com/oauthplayground

but this token is expired every 3600 seconds. so I visit the page again and press the button "Refresh access token" to get another one and use it again in above code.

Is this the correct method of accessing my blog and dynamically posting contents and articles programmatically?

Second

In google developers console https://developers.google.com/console i saw that I have 10000 requests/day and a limit of 1 request/second/user

BUT

after correctly posting dynamically using my above code around 50 posts (note that I set a wait for around 5 seconds between a consecutive requests), I started receiving the following error from the api call:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "usageLimits",
    "message" : "Rate Limit Exceeded",
    "reason" : "rateLimitExceeded"
  } ],
  "message" : "Rate Limit Exceeded"
}

I return to my quota page and I see that the requests that I send did not decreased from my allowed requests per day !!!

Some my second question is:

Does I forget a specific configuration for correctly manipulate my blog dynamically ?

Thank you in advance for your help and support.

回答1:

There is no way to preauthorize someone for Blogger so I believe the only way to access Blogger Api is to generate access token through Auth 2 Playground and then using the token for API call.

Even though it shows 10000 requests/day and a limit of 1 request/second/user on the console, the fact is Blogger api only permit maximum 50 requests per day by default. Till a while back there was provision to request additional quota by specifying genuine need for it which has now been discontinued.



回答2:

You can generate the api token through your code instead of generating it from the playground. However you have to authenticate on the first time.

private static GoogleCredential getCredentials(HttpTransport httpTransport, JacksonFactory jacksonFactory,
        List<String> scopes) throws IOException, GeneralSecurityException {
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory,
            CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").build();
    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println("Please open the following URL in your " + "browser then type the authorization code:");
    System.out.println("  " + url);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String code = br.readLine();
    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    System.out.println("Response : " + response.toPrettyString());
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(jacksonFactory).setServiceAccountId("xyz@gmail.com")
            .setServiceAccountPrivateKeyFromP12File(new File("resources\\xyz.p12"))
            .setServiceAccountScopes(Collections.singleton(BloggerScopes.BLOGGER)).build();
    credential.setAccessToken(response.getAccessToken());
    return credential;
}

public static Blogger getBlog() throws IOException, GeneralSecurityException, AuthenticationException {
    if (blog == null) {
        if (httpTransport == null)
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        if (jacksonFactory == null)
            jacksonFactory = JacksonFactory.getDefaultInstance();
        blog = new Blogger.Builder(httpTransport, jacksonFactory,
                getCredentials(httpTransport, jacksonFactory, Arrays.asList(BloggerScopes.BLOGGER)))
                        .setApplicationName("Blogger").build();
    }
    return blog;
}

public static void udpatePost(String title, String content) throws IOException, AuthenticationException, GeneralSecurityException{
    Post post = new Post();
    post.setTitle(title);
    post.setContent(content);
    Update updateAction = getBlog().posts().update(BLOG_ID, POST_ID, post);
    updateAction.setFields("author/displayName,content,published,title,url");
    post = updateAction.execute();
    System.out.println("Published: " + post.getPublished());  
}

JARs for API v3 Client Library: http://developers.google.com/blogger/docs/3.0/api-lib/java