使用Java / App Engine - 错误401向Blogger发送API请求的正确形式 [英] Proper Form of API request to Blogger using Java/App Engine -error 401

查看:143
本文介绍了使用Java / App Engine - 错误401向Blogger发送API请求的正确形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经通过Google云端控制台测试了我的声明,它可以正常工作但在我的代码中不起作用。我使用的是Google App Engine,并被授权使用Blogger。授权也与运行Google App Engine的帐户绑定。



任何想法都会有帮助。周末已经尝试了很多事情。



感谢

 请求
GET https://www.googleapis.com/blogger / V3 /博客/ 7676001971884966148 /职位键= {} YOUR_API_KEY

授权:承载ya29.1.AADtN_Vd7lKj8Xy3KbZ1veJjjjv712Nc1erLY2dmAK3gorNilVd0652vnqrrovfuLfSKkQ
X-JavaScript的用户代理:谷歌API浏览器


响应
200 OK

- 显示标题 -

{
kind:blogger#postList,
nextPageToken:CgkIChjim-ftqygQhIKb6_zjqMNq,
items:[
{
etc .....
pre>

我的代码

  public class BloggerHandler 
{

public static final Logger log = Logger.getLogger(BloggerHandler.class.getName());

public void testCreds()抛出异常{
try {
ArrayList< String> scopes = new ArrayList< String>();
scopes.add(https://www.googleapis.com/auth/blogger);
scopes.add(https://www.googleapis.com/auth/blogger.readonly);


AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
//令牌声明由appIdentity.getServiceAccountName()报告的身份
JSONObject request = new JSONObject();
//request.put(maxPosts,1);

//request.put(view,AUTHOR);

log.info(request !!!+ request);

网址=新网址(https://www.googleapis.com/blogger/v3/blogs/7676001971884966148/posts?);
log.info(URL:+ url);
HttpURLConnection连接=(HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod(GET);
connection.addRequestProperty(Content-Type,application / json);
connection.addRequestProperty(授权,OAuth+ accessToken.getAccessToken());

log.info(Con !!+ connection);


OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
request.write(writer);
writer.close();
log.info(connection:+ connection.getResponseCode());
if(connection.getResponseCode()== HttpURLConnection.HTTP_OK){
//注意:应该检查内容编码。
JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
JSONObject response = new JSONObject(response_tokens);

log.info(resp:+ response.get(title));




} // end if

else {
throw new Exception();
} // end else

// end try

catch(Exception e){
//错误处理消失。
log.info(ex:+ e);


}
//结束捕获



} //结束空白


} // end class


解决方案

很少的漫长的夜晚,我能够想出如何从GAE项目访问Google Blogger API。



我做了几件关键事情,可能有助于帮助您。


  • 在您的Google Appe Engine项目中,确保它已链接到Google API控制台。在GAE Admin项目屏幕中,您应该看到一个 Google API控制台项目编号:XX

  • 您已获得Blogger授权(或您希望使用的任何云API)。创建一个项目(网站..等),并复制它给你的API字符串。


一旦你有了这个API字符串下面的代码应该让你开始使用基础连接。



下面的代码应该返回一个200连接,其中包含你试图访问的当前博客的统计数据。从这里您可以扩展API。



//在附注中,我知道有一种方法可以从Google Cloud中读取API,因此它不必是部分代码。仍在处理该工作流程。

  import java.util.logging.Logger; 
import java.util.Arrays;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.services.blogger.Blogger;
import com.google.api.services.blogger.Blogger.Blogs.GetByUrl;
import com.google.api.services.blogger.Blogger.Posts.List;
import com.google.api.services.blogger.BloggerScopes;
import com.google.api.services.blogger.model.Blog;
import com.google.api.services.blogger.model.Post;
import com.google.api.services.blogger.model.PostList;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import java.io.IOException;

public class BlogHandler
{
public Blogger blogger = null;
公开博客博客;
public java.util.List< Post>帖子;
public static final Logger log = Logger.getLogger(EngineParseFeed.class.getName());
static final String API_KEY ={您的GOOGLE CLOUD API};
$ b $ public BlogHandler(){}
$ b public void setupService()throws IOException {

AppIdentityCredential credential = null;
credential = new AppIdentityCredential(Arrays.asList(BloggerScopes.BLOGGER)); //添加你的作用域
this.blogger = new Blogger.Builder(new UrlFetchTransport(),new JacksonFactory(),凭证).setApplicationName(trivalAPPName)。build();
}

public void executeGetBlogByUrl(String url)throws IOException {
GetByUrl request = blogger.blogs()。getByUrl(url);
this.blog = request.setKey(API_KEY).execute();
log.info(Blog+ this.blog);
}


I am running into issue in forming the correct api statement for JAVA in calling the Blogger API.

I have tested my statement via the Google Cloud Console and it works but does not work in my code. I am using Google App Engine and have been authorized to use Blogger. The authorization is also tied to the account running Google App Engine.

Any ideas would be helpfull.. have tried many things over the weekend.

Thanks

Request
GET https://www.googleapis.com/blogger/v3/blogs/7676001971884966148/posts?key=   {YOUR_API_KEY}

Authorization:  Bearer ya29.1.AADtN_Vd7lKj8Xy3KbZ1veJjjjv712Nc1erLY2dmAK3gorNilVd0652vnqrrovfuLfSKkQ
X-JavaScript-User-Agent:  Google APIs Explorer


Response
200 OK

- Show headers -

{
"kind": "blogger#postList",
"nextPageToken": "CgkIChjim-ftqygQhIKb6_zjqMNq",
"items": [
{
etc.....

My Code

public class BloggerHandler
{

  public static final Logger log = Logger.getLogger(BloggerHandler.class.getName());

public void testCreds() throws Exception  {
   try{
   ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/blogger");
    scopes.add("https://www.googleapis.com/auth/blogger.readonly");


    AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    // The token asserts the identity reported by appIdentity.getServiceAccountName()
    JSONObject request = new JSONObject();
   //request.put("maxPosts", "1");

   //request.put("view", "AUTHOR");

    log.info("request!!!" + request);

     URL url = new URL("https://www.googleapis.com/blogger/v3/blogs/7676001971884966148/posts?");
     log.info("URL:" + url);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Authorization", "OAuth" + accessToken.getAccessToken());

    log.info("Con!!" + connection);


    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    request.write(writer);
    writer.close();
     log.info("connection:" + connection.getResponseCode());
     if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // Note: Should check the content-encoding.
        JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
        JSONObject response = new JSONObject(response_tokens);

        log.info("resp:" + response.get("title")); 




     } // end if 

     else {
        throw new Exception();
     }// end else

     } // end try

     catch (Exception e) {
    // Error handling elided.
    log.info("ex:" + e);


    }
// end catch



}// end void


}// end class

解决方案

After a few long nights I was able to figure out how to access the Google Blogger API from a GAE project.

There are a couple of key things that I did that may help aid you.

  • In your Google Appe Engine project make sure that it is linked to the Google API Console. IN the GAE Admin project screen you should see a Google APIs Console Project Number:XX
  • In the Google API Cloud console make sure you are authorized for Blogger (or whatever cloud API you want to use). Create a project (website.. etc) and copy down the API string that it gives you.

Once you have that API string the code below should get you started with base connection.

The code below should return a "200" connection with the stats of the current blog you are trying to reach. From here you can expand upon the API.

// On a side note I know there is a way to read the API from Google Cloud so it does not have to be part of the code. Still working on that workflow.

import java.util.logging.Logger;
import java.util.Arrays;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.services.blogger.Blogger;
import com.google.api.services.blogger.Blogger.Blogs.GetByUrl;
import com.google.api.services.blogger.Blogger.Posts.List;
import com.google.api.services.blogger.BloggerScopes;
import com.google.api.services.blogger.model.Blog;
import com.google.api.services.blogger.model.Post;
import com.google.api.services.blogger.model.PostList;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import java.io.IOException;

public class BlogHandler
{
  public Blogger blogger = null;
  public Blog blog;
  public java.util.List<Post> posts;
  public static final Logger log = Logger.getLogger(EngineParseFeed.class.getName());
  static final String API_KEY = "{Your GOOGLE CLOUD API}";

  public BlogHandler() {}

  public void setupService () throws IOException {

    AppIdentityCredential credential = null;
    credential  = new AppIdentityCredential(Arrays.asList(BloggerScopes.BLOGGER)); // Add your scopes here
    this.blogger = new Blogger.Builder(new UrlFetchTransport(), new JacksonFactory(), credential).setApplicationName("trivalAPPName").build();
   }

   public void executeGetBlogByUrl (String url) throws IOException {
     GetByUrl request = blogger.blogs().getByUrl( url );
     this.blog = request.setKey(API_KEY).execute();
     log.info ("Blog" + this.blog);
   }

这篇关于使用Java / App Engine - 错误401向Blogger发送API请求的正确形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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