1package com.squareup.okhttp.guide;
2
3import com.squareup.okhttp.OkHttpClient;
4import java.io.ByteArrayOutputStream;
5import java.io.IOException;
6import java.io.InputStream;
7import java.net.HttpURLConnection;
8import java.net.URL;
9
10public class GetExample {
11  OkHttpClient client = new OkHttpClient();
12
13  void run() throws IOException {
14    String result = get(new URL("https://raw.github.com/square/okhttp/master/README.md"));
15    System.out.println(result);
16  }
17
18  String get(URL url) throws IOException {
19    HttpURLConnection connection = client.open(url);
20    InputStream in = null;
21    try {
22      // Read the response.
23      in = connection.getInputStream();
24      byte[] response = readFully(in);
25      return new String(response, "UTF-8");
26    } finally {
27      if (in != null) in.close();
28    }
29  }
30
31  byte[] readFully(InputStream in) throws IOException {
32    ByteArrayOutputStream out = new ByteArrayOutputStream();
33    byte[] buffer = new byte[1024];
34    for (int count; (count = in.read(buffer)) != -1; ) {
35      out.write(buffer, 0, count);
36    }
37    return out.toByteArray();
38  }
39
40  public static void main(String[] args) throws IOException {
41    new GetExample().run();
42  }
43}
44