• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 com.squareup.okhttp.Request;
7 import com.squareup.okhttp.Response;
8 import com.squareup.okhttp.ResponseBody;
9 import java.io.Reader;
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 
main(String... args)26   public static void main(String... args) throws Exception {
27     OkHttpClient client = new OkHttpClient();
28 
29     // Create request for remote resource.
30     Request request = new Request.Builder()
31         .url(ENDPOINT)
32         .build();
33 
34     // Execute the request and retrieve the response.
35     Response response = client.newCall(request).execute();
36 
37     // Deserialize HTTP response to concrete type.
38     ResponseBody body = response.body();
39     Reader charStream = body.charStream();
40     List<Contributor> contributors = GSON.fromJson(charStream, CONTRIBUTORS.getType());
41     body.close();
42 
43     // Sort list by the most contributions.
44     Collections.sort(contributors, new Comparator<Contributor>() {
45       @Override public int compare(Contributor c1, Contributor c2) {
46         return c2.contributions - c1.contributions;
47       }
48     });
49 
50     // Output list of contributors.
51     for (Contributor contributor : contributors) {
52       System.out.println(contributor.login + ": " + contributor.contributions);
53     }
54   }
55 
OkHttpContributors()56   private OkHttpContributors() {
57     // No instances.
58   }
59 }
60