2016-05-13 8 views
2

これはStackOverflowに関する私の最初の質問ですので、私が無視したことがある場合は教えてください!Blogger APIサンプルコード

私が行っているいくつかの言語分析研究のために、Bloggerの公開ブログからブログ投稿データを取得しようとしています。 Java APIはかなり簡単ですが、LocalServerReceiver()からOAuthorizationに必要なすべての依存関係まで多くの依存関係がないため、https://developers.google.com/blogger/docs/3.0/reference/posts/list#examplesのGoogleのコードサンプルは機能しません。 APIエクスプローラはうまく動作しますが、明らかに私自身のコードには何かが必要です。

私は他のStackOverflow質問からのコードフラグメントを利用しようとしましたが、それは私のものと似ていましたが、依然として依存関係の問題に直面しています。

ここで原因コードの廃止のいくつかの並べ替えに私の問題を解決していない私が見てきた質問のいくつかのリストです:

私はOAuthPlaygroundを使用して認証コードを取得し、Proper Form of API request to Blogger using Java/App Engine -error 401のiamkhovaのソリューションの機能の一部を複製しようとしています。私が実際にアクセスしているブログには何も書き込もうとしていないことに注意してください。私はちょうど分析のためのポストデータを得ることができるようにしたい。

現在、私はロガーを取り出し、Googleのサンプルコードから必要なものを複製するgetPosts()関数を追加するだけで、iamkhovaのソリューションを変更しました。

public class BlogHandler 
{ 
    static final String API_KEY = {My API Key}; 
    public Blogger blogger = null; 
    public Blog blog; 
    public java.util.List<Post> posts; 

    public BlogHandler() {} 

    public void executeGetBlogByUrl (String url) throws IOException { 
    GetByUrl request = blogger.blogs().getByUrl(url); 
    this.blog = request.setKey(API_KEY).execute(); 

    } 
    public void getPosts() throws IOException 
    { 
     List postsListAction = blogger.posts().list(this.blog.getId()); 

    // Restrict the result content to just the data we need. 
    postsListAction.setFields("items(author/displayName,content,published,title,url),nextPageToken"); 

    // This step sends the request to the server. 
    PostList posts = postsListAction.execute(); 

    // Now we can navigate the response. 
    int postCount = 0; 
    int pageCount = 0; 
    while (posts.getItems() != null && !posts.getItems().isEmpty()) { 
      for (Post post : posts.getItems()) { 
        System.out.println("Post #"+ ++postCount); 
        System.out.println("\tTitle: "+post.getTitle()); 
        System.out.println("\tAuthor: "+post.getAuthor().getDisplayName()); 
        System.out.println("\tPublished: "+post.getPublished()); 
        System.out.println("\tURL: "+post.getUrl()); 
        System.out.println("\tContent: "+post.getContent()); 
      } 

      // Pagination logic 
      String pageToken = posts.getNextPageToken(); 
      if (pageToken == null || ++pageCount >= 5) { 
        break; 
      } 
      System.out.println("-- Next page of posts"); 
      postsListAction.setPageToken(pageToken); 
      posts = postsListAction.execute(); 
    } 

    } 

    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("chsBlogResearch").build(); 
    } 

} 

現在、私は次のエラーを持っている:MemcacheServiceImplとAppIdentityServiceImplでエラーの両方のためのコード行をクリック

Exception in thread "main" com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'memcache' or call 'Get()' was not found. 
    at com.google.apphosting.api.ApiProxy$1.get(ApiProxy.java:173) 
    at com.google.apphosting.api.ApiProxy$1.get(ApiProxy.java:171) 
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89) 
    at com.google.appengine.api.memcache.MemcacheServiceImpl.quietGet(MemcacheServiceImpl.java:26) 
    at com.google.appengine.api.memcache.MemcacheServiceImpl.get(MemcacheServiceImpl.java:49) 
    at com.google.appengine.api.appidentity.AppIdentityServiceImpl.getAccessToken(AppIdentityServiceImpl.java:286) 
    at com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential.intercept(AppIdentityCredential.java:98) 
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469) 
    at BloggerData.BlogHandler.executeGetBlogByUrl(BlogHandler.java:29) 

は、その時点でのコードのない行が存在しないことを教えてください。依存関係のためにEclipse内でMavenを使用しています。

このコードで私が本当にわからないのはスコープのアイデアだけですが、それが私のエラーの原因になっているとは思いません。

この投稿データを取得するのは、思ったよりも時間がかかりました。

更新:getting strange exception trying to implement asynchronous http in google app engine for java上記のエラーに関するもう少し詳しい情報が提供されました。どうやら、このApiProxy jarはコンソールアプリケーションから呼び出すことはできません。

+0

あなたは何をURLとしてexecuteGetBlogByUrl()メソッドに渡していますか? – ManoDestra

+0

現在のところ、ランダムなブログのURLの文字列(私のものではなく、テスト目的のもの)です。私は、ブログが実際にBloggerのブログであることを最初に確認しました。 – tatertot

+0

ManoDestraはあなたの質問に基づいて、より良いテスト用のURL(実際に私のものです)を試してみることにしました - ここにブログがあります:https://chstesting.blogspot.com/ – tatertot

答えて

1

実際には非常に有用な答えですが、それが私の状況で働いてしまったのです。

Google Java APIクライアントは古くなっているので、代わりにGoogle API Pythonクライアントに切り替えることになりました。更新されているため、OAuthは実際にPythonクライアントで動作します。それはhttps://github.com/google/google-api-python-clientにあります。サンプルファイルは非常に便利で、実際には直感的です。

GoogleのJava APIのサンプルは、少なくともBlogger側のものすべてが壊れていることに注意してください。

0

複数のリンクから、私はblogger api v3(api keyとoauth2資格情報を使用)のために次のスタンドアロンJavaクラスWORKINGを得ました。私は手動でコンソール上の要求URIからのトークンを貼り付ける必要があります。

import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 
    import java.security.GeneralSecurityException; 
    import java.util.Arrays; 
    import java.util.List; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.entity.StringEntity; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONException; 
    import org.json.JSONObject; 
    import com.google.api.client.auth.oauth2.Credential; 
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 
    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
    import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
    import com.google.api.client.http.HttpTransport; 
    import com.google.api.client.http.javanet.NetHttpTransport; 
    import com.google.api.client.json.jackson2.JacksonFactory; 
    import com.google.api.services.blogger.BloggerScopes; 


    public class PostInsert { 
     private static final String REDIRECT_URI = "YOUR REDIRECT URI"; 
     private static final String CLIENT_SECRET = "YOUR CLIENT SECRET"; 
     private static final String CLIENT_ID = "YOUR CLIENT_ID"; 

     public static void main(String[] args) { 

      try { 
       HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 
       JacksonFactory JSON_FACTORY = new JacksonFactory(); 
       Credential credential = getCredentials(HTTP_TRANSPORT, JSON_FACTORY, Arrays.asList(BloggerScopes.BLOGGER)); 

       final JSONObject obj = new JSONObject(); 
       obj.put("id", "<enter your blogid>"); 

       final JSONObject requestBody = new JSONObject();     

       requestBody.put("title", "adding on 15feb 1.56pm"); 

       requestBody.put("content", "add this"); 

       final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/<enter your blogid>/posts?key=<enter your api key>"); 
       request.addHeader("Authorization", "Bearer " + credential.getAccessToken()); 
       request.addHeader("Content-Type", "application/json"); 
       HttpClient mHttpClient = new DefaultHttpClient(); 
       request.setEntity(new StringEntity(requestBody.toString())); 
       final HttpResponse response = mHttpClient.execute(request); 
       System.out.println(response.getStatusLine().getStatusCode() + " " + 
         response.getStatusLine().getReasonPhrase() 
         ); 
      } catch (JSONException | IOException | GeneralSecurityException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

      public 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) 
          .setClientSecrets(CLIENT_ID, CLIENT_SECRET) 
          .build(); 
       credential.setAccessToken(response.getAccessToken()); 
       return credential; 
      }  
    } 
関連する問題