Home | History | Annotate | Download | only in sample
      1 package com.squareup.okhttp.sample;
      2 
      3 import com.google.gson.Gson;
      4 import com.google.gson.reflect.TypeToken;
      5 import com.squareup.okhttp.OkHttpClient;
      6 import java.io.InputStream;
      7 import java.io.InputStreamReader;
      8 import java.net.HttpURLConnection;
      9 import java.net.URL;
     10 import java.util.Collections;
     11 import java.util.Comparator;
     12 import java.util.List;
     13 
     14 public class OkHttpContributors {
     15   private static final String ENDPOINT = "https://api.github.com/repos/square/okhttp/contributors";
     16   private static final Gson GSON = new Gson();
     17   private static final TypeToken<List<Contributor>> CONTRIBUTORS =
     18       new TypeToken<List<Contributor>>() {
     19       };
     20 
     21   static class Contributor {
     22     String login;
     23     int contributions;
     24   }
     25 
     26   public static void main(String... args) throws Exception {
     27     OkHttpClient client = new OkHttpClient();
     28 
     29     // Create request for remote resource.
     30     HttpURLConnection connection = client.open(new URL(ENDPOINT));
     31     InputStream is = connection.getInputStream();
     32     InputStreamReader isr = new InputStreamReader(is);
     33 
     34     // Deserialize HTTP response to concrete type.
     35     List<Contributor> contributors = GSON.fromJson(isr, CONTRIBUTORS.getType());
     36 
     37     // Sort list by the most contributions.
     38     Collections.sort(contributors, new Comparator<Contributor>() {
     39       @Override public int compare(Contributor c1, Contributor c2) {
     40         return c2.contributions - c1.contributions;
     41       }
     42     });
     43 
     44     // Output list of contributors.
     45     for (Contributor contributor : contributors) {
     46       System.out.println(contributor.login + ": " + contributor.contributions);
     47     }
     48   }
     49 
     50   private OkHttpContributors() {
     51     // No instances.
     52   }
     53 }
     54