使用Java验证自己的Blogger API的Google帐户 [英] Authenticate own Google account for Blogger API with Java

查看:55
本文介绍了使用Java验证自己的Blogger API的Google帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个将本地文件发布到Google Blogger的机器人.我将是唯一使用此应用程序的人,因此不需要设置用户友好的身份验证例程.我花了一个晚上试图进行设置,但我仍在为OAuth请求而苦苦挣扎.

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.

我创建了一个新的Google应用程序项目(类型:已安装的桌面应用程序),并将Blogger API添加为作用域,然后导出了自己帐户的客户秘密文件(google-credentials.json,请参见下文).

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).

代码:

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:

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"
    ]
  }
}

响应:

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."
}

我也尝试了GoogleAuthorizationCodeFlow + GoogleTokenResponse,但是我不知道在哪里注册令牌响应,因为似乎不允许使用新的GoogleCredential().setFromTokenResponse().

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.

我从Google找到的示例已有几年历史,并且导入了AuthorizationCodeInstalledApp,它不是我的依赖项com.google.apis:google-api-services-blogger:v3-rev50-1.21.0的类.

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.

推荐答案

我遇到了同样的问题,我这样解决了:

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

我还需要在pom.xml(Maven项目)中设置以下依赖项

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>

这篇关于使用Java验证自己的Blogger API的Google帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆