• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.squareup.okhttp.recipes;
17 
18 import com.google.gson.Gson;
19 import com.squareup.okhttp.OkHttpClient;
20 import com.squareup.okhttp.Request;
21 import com.squareup.okhttp.Response;
22 import java.io.IOException;
23 import java.util.Map;
24 
25 public final class ParseResponseWithGson {
26   private final OkHttpClient client = new OkHttpClient();
27   private final Gson gson = new Gson();
28 
run()29   public void run() throws Exception {
30     Request request = new Request.Builder()
31         .url("https://api.github.com/gists/c2a7c39532239ff261be")
32         .build();
33     Response response = client.newCall(request).execute();
34     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
35 
36     Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
37     for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
38       System.out.println(entry.getKey());
39       System.out.println(entry.getValue().content);
40     }
41   }
42 
43   static class Gist {
44     Map<String, GistFile> files;
45   }
46 
47   static class GistFile {
48     String content;
49   }
50 
main(String... args)51   public static void main(String... args) throws Exception {
52     new ParseResponseWithGson().run();
53   }
54 }
55