google-http-java-client(android学习篇2源码)

时间:2022-05-05 15:23:58
package com.google.api.services.samples.googleplus.cmdline.simple;
 
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Key;
 
import java.io.IOException;
import java.util.List;
 
/**
 * Simple example that demonstrates how to use <a
 * href="code.google.com/p/google-http-java-client/">Google HTTP Client Library for Java</a> with
 * the <a href="https://developers.google.com/+/api/">Google+ API</a>.
 *
 * <p>
 * Note that in the case of the Google+ API, there is a much better custom library built on top of
 * this HTTP library that is much easier to use and hides most of these details for you. See <a
 * href="http://code.google.com/p/google-api-java-client/wiki/APIs#Google+_API">Google+ API for
 * Java</a>.
 * </p>
 *
 * @author Yaniv Inbar
 */
publicclassGooglePlusSample{
 
  privatestaticfinalString API_KEY =
      "Enter API Key from https://code.google.com/apis/console/?api=plus into API_KEY";
 
  privatestaticfinalString USER_ID ="116899029375914044550";
  privatestaticfinalint MAX_RESULTS =3;
 
  staticfinalHttpTransport HTTP_TRANSPORT =newNetHttpTransport();
  staticfinalJsonFactory JSON_FACTORY =newJacksonFactory();
 
  /** Feed of Google+ activities. */
  publicstaticclassActivityFeed{
 
    /** List of Google+ activities. */
    @Key("items")
    privateList<Activity> activities;
 
    publicList<Activity> getActivities(){
      return activities;
    }
  }
 
  /** Google+ activity. */
  publicstaticclassActivityextendsGenericJson{
 
    /** Activity URL. */
    @Key
    privateString url;
 
    publicString getUrl(){
      return url;
    }
 
    /** Activity object. */
    @Key("object")
    privateActivityObject activityObject;
 
    publicActivityObject getActivityObject(){
      return activityObject;
    }
  }
 
  /** Google+ activity object. */
  publicstaticclassActivityObject{
 
    /** HTML-formatted content. */
    @Key
    privateString content;
 
    publicString getContent(){
      return content;
    }
 
    /** People who +1'd this activity. */
    @Key
    privatePlusOners plusoners;
 
    publicPlusOners getPlusOners(){
      return plusoners;
    }
  }
 
  /** People who +1'd an activity. */
  publicstaticclassPlusOners{
 
    /** Total number of people who +1'd this activity. */
    @Key
    privatelong totalItems;
 
    publiclong getTotalItems(){
      return totalItems;
    }
  }
 
  /** Google+ URL. */
  publicstaticclassPlusUrlextendsGenericUrl{
 
    publicPlusUrl(String encodedUrl){
      super(encodedUrl);
    }
 
    @SuppressWarnings("unused")
    @Key
    privatefinalString key = API_KEY;
 
    /** Maximum number of results. */
    @Key
    privateint maxResults;
 
    publicint getMaxResults(){
      return maxResults;
    }
 
    publicPlusUrl setMaxResults(int maxResults){
      this.maxResults = maxResults;
      returnthis;
    }
 
    /** Lists the public activities for the given Google+ user ID. */
    publicstaticPlusUrl listPublicActivities(String userId){
      returnnewPlusUrl(
          "https://www.googleapis.com/plus/v1/people/"+ userId +"/activities/public");
    }
  }
 
  privatestaticvoid parseResponse(HttpResponse response)throwsIOException{
    ActivityFeed feed = response.parseAs(ActivityFeed.class);
    if(feed.getActivities().isEmpty()){
      System.out.println("No activities found.");
    }else{
      if(feed.getActivities().size()== MAX_RESULTS){
        System.out.print("First ");
      }
      System.out.println(feed.getActivities().size()+" activities found:");
      for(Activity activity : feed.getActivities()){
        System.out.println();
        System.out.println("-----------------------------------------------");
        System.out.println("HTML Content: "+ activity.getActivityObject().getContent());
        System.out.println("+1's: "+ activity.getActivityObject().getPlusOners().getTotalItems());
        System.out.println("URL: "+ activity.getUrl());
        System.out.println("ID: "+ activity.get("id"));
      }
    }
  }
 
  privatestaticvoid run()throwsIOException{
    HttpRequestFactory requestFactory =
        HTTP_TRANSPORT.createRequestFactory(newHttpRequestInitializer(){
            @Override
          publicvoid initialize(HttpRequest request){
            request.setParser(newJsonObjectParser(JSON_FACTORY));
          }
        });
    PlusUrl url =PlusUrl.listPublicActivities(USER_ID).setMaxResults(MAX_RESULTS);
    url.put("fields","items(id,url,object(content,plusoners/totalItems))");
    HttpRequest request = requestFactory.buildGetRequest(url);
    parseResponse(request.execute());
  }
 
  publicstaticvoid main(String[] args){
    if(API_KEY.startsWith("Enter ")){
      System.err.println(API_KEY);
      System.exit(1);
    }
    try{
      try{
        run();
        return;
      }catch(HttpResponseException e){
        System.err.println(e.getMessage());
      }
    }catch(Throwable t){
      t.printStackTrace();
    }
    System.exit(1);
  }
}