How to download image file by using okhttpclient in Java

user3338304 picture user3338304 · Nov 1, 2014 · Viewed 18.5k times · Source

I would like ask how to download image file by using okhttpclient in Java since I need to download the file with session.
here is the code given officially, but I don't know how to use it for downloading as image file.

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }

    System.out.println(response.body().string());
  }

Answer

Jodi Goddard picture Jodi Goddard · Dec 3, 2014

Try something like this

InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);