如何在Google Plus中获得帖子的评论?

时间:2012-09-11 06:04:40

标签: google-api oauth-2.0 google-plus google-api-java-client

如何在Google +上收到帖子的评论?

我已经收到了帖子的内容和回复的数量。

public class Sample {

  private static Plus unauthenticatedPlus;

  public static void main(String[] args) throws IOException {

    try {
      setupTransport();

      getActivity();
    } catch (HttpResponseException e) {
      /* ... */
    }
  }

  /**
   * Setup the transport for our API calls.
   * @throws java.io.IOException when the transport cannot be created
   */
   private static void setupTransport() throws IOException {
       // Here's an example of an unauthenticated Plus object. In cases where you
       // do not need to use the /me/ path segment to discover the current user's
       // ID, you can skip the OAuth flow with this code.
       unauthenticatedPlus = Plus.builder(Util.TRANSPORT, Util.JSON_FACTORY)
           // When we do not specify access tokens, we must specify our API key instead
           // We do this using a JsonHttpRequestInitializer
           .setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
               @Override
               public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException {
                 PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
                 plusRequest.setKey(Auth.GOOGLE_API_KEY);
               }
       }).build();

      /* Authorization part stripped, as this is not needed in this sample */
      /* ... */
  }

  /**
   * Get the most recent activity for the authenticated user.
   *
   * @throws IOException if unable to call API
   */
  private static void getActivity() throws IOException {
    // A known public activity ID
    String activityId = "z12gtjhq3qn2xxl2o224exwiqruvtda0i";

    /* Get an explicit public activity by ID */
    // We do not need to be authenticated to fetch this activity
    try {
      Activity activity = unauthenticatedPlus.activities().get(activityId).execute();
      show(activity);
    } catch (HttpResponseException e) {
      /* ... */
    }
  }

  /**
   * Print the specified activity on the command line.
   *
   * @param activity the activity to show
   */
  private static void show(Activity activity) {
    System.out.println("id: " + activity.getId());
    System.out.println("url: " + activity.getUrl());
    System.out.println("content: " + activity.getPlusObject().getContent());
    System.out.println("No of replies: " + activity.getPlusObject().getReplies().getTotalItems());
  }
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

获取活动评论需要

制作新的extra request

Plus.Comments.List listComments = plus.comments().list(activityId);

执行请求并将其解析为PlusRequest instance

CommentFeed commentFeed = listComments.execute();

获取CommentFeed个实例的列表:

List<Comment> comments = commentFeed.getItems();