如何在Java中使用okhttpclient下载图像文件

ego6inou  于 2023-01-29  发布在  Java
关注(0)|答案(4)|浏览(229)

我想问一下如何使用Java中的okhttpclient下载图像文件,因为我需要使用会话下载文件。
这是官方给出的代码,但我不知道如何使用它作为图像文件下载。

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

blpfk2vs1#

试试这个

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

n3schb8v2#

也许现在回答这个问题有点晚了,但它可能会在未来帮助一些人。我喜欢总是在后台下载照片,使用OkHttpClient这样做,你应该使用回调:

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

cbjzeqam3#

我用的是近似代码:

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; 
}
agxfikkp

agxfikkp4#

您可以使用以下代码:

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

仅仅9年后:),为每个需要它的人。

相关问题