user3338304
user3338304

Reputation: 291

How to download image file by using okhttpclient in Java

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());
  }

Upvotes: 26

Views: 26673

Answers (4)

Nader
Nader

Reputation: 29

You can use this code below:

byte[] bufferedImage =  response.body().source().readByteArray();
Image image = new Image(new ByteArrayInputStream(bufferedImage));

It is just 9 years later :), for everyone who needs it.

Upvotes: 0

Pivoter
Pivoter

Reputation: 419

I'm using approximately code:

public boolean saveImage(Response response) throws IOException {

    // check response/body for null
   
    InputStream inputStream = response.body().byteStream();
    File file = new File("filename.jpg");
    BufferedImage image = ImageIO.read(inputStream);
    ImageIO.write(image, "jpg", file);

    if (file.exists())
      return true;

    return false; 
}

Upvotes: 0

OfcOurSe
OfcOurSe

Reputation: 121

Maybe it is a bit late to answer the question, but it may helps someone in the future. I prefer always to download photos in background, to do so using OkHttpClient, you should use callback:

    final Request request = new Request.Builder().url(url).build();
    okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //Handle the error
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()){
                        final Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                       // Remember to set the bitmap in the main thread.
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    imageView.setImageBitmap(image);
                                }
                            });
                    }else {
                        //Handle the error
                    }
                }
            });

Upvotes: 12

Jodi Goddard
Jodi Goddard

Reputation: 384

Try something like this

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

Upvotes: 35

Related Questions