Authenticate own Google account for Blogger API with Java

做~自己de王妃 提交于 2019-12-12 20:44:02

问题


I want to write a bot that posts local files to Google Blogger. I will be the only one using this application, so I don't need to setup a user friendly authentication routine. I spent an evening trying to set things up and I'm still struggling with the OAuth requests.

I created a new Google app project (type: installed desktop app) and added the Blogger API as scope, then I exported a client secret file for my own account (google-credentials.json, see below).

Code:

try
{
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    List<String> scopes = Arrays.asList(BloggerScopes.BLOGGER);

    GoogleClientSecrets secrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(Main.class.getResourceAsStream("/google-credentials.json")));

    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
                                                                .setTransport(httpTransport)
                                                                .setClientSecrets(secrets)
                                                                .build();

    Blogger blogger = new Blogger.Builder(httpTransport, jsonFactory, credential).setApplicationName("jd34app")
                                                                                 .build();

    blogger.blogs().getByUrl("http://jd34blog.blogspot.com").execute();
}
catch (Exception e)
{
    e.printStackTrace();
}

google-credentials.json:

{
  "installed": {
    "client_id": "<removed>",
    "project_id": "<removed>",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "<removed>",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob",
      "http://localhost"
    ]
  }
}

Response:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "usageLimits",
    "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "reason" : "dailyLimitExceededUnreg",
    "extendedHelp" : "https://code.google.com/apis/console"
  } ],
  "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}

I also tried GoogleAuthorizationCodeFlow + GoogleTokenResponse, but I don't know where to register the token response, because new GoogleCredential().setFromTokenResponse() seems to be not allowed.

The examples from Google I found are some years old and import AuthorizationCodeInstalledApp which is not a class of my dependency com.google.apis:google-api-services-blogger:v3-rev50-1.21.0.


回答1:


I had the same problem, i solved like this:

private static Credential authorize() throws Exception 
   {
   HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
   JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
   List<String> scopes = Arrays.asList(BloggerScopes.BLOGGER);

   // load client secrets
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(clientId_File)));

  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
     httpTransport, jsonFactory, clientSecrets, scopes).build();

 // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

protected void doTest2() throws Exception 
    {
    // Configure the Installed App OAuth2 flow.
    Credential credential = authorize();

    Blogger blogger = new Blogger.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).setHttpRequestInitializer(credential)
            .build();

    // The request action object.
    GetByUrl blogGetByUrlAction = blogger.blogs().getByUrl(BLOG_URL);

    // Configure which blog URL to look up.
    blogGetByUrlAction.setUrl(BLOG_URL);

    // Restrict the result content to just the data we need.
    blogGetByUrlAction.setFields("description,name,posts/totalItems,updated");

    // This step sends the request to the server.
    Blog blog = blogGetByUrlAction.execute();

    // Now we can navigate the response.
    System.out.println("Name: " + blog.getName());
    System.out.println("Description: " + blog.getDescription());
    System.out.println("Post Count: " + blog.getPosts().getTotalItems());
    System.out.println("Last Updated: " + blog.getUpdated());
}

I also need to set the following dependencies in my pom.xml (maven project)

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.20.0</version>
</dependency>
<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client-java6</artifactId>
    <version>1.20.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.21.0</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-blogger</artifactId>
    <version>v3-rev50-1.21.0</version>
</dependency>


来源:https://stackoverflow.com/questions/35369919/authenticate-own-google-account-for-blogger-api-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!