java 如何在Java中使用okhttpclient下载图片文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26689464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download image file by using okhttpclient in Java
提问by user3338304
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.
我想问一下如何在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());
}
回答by Jodi Goddard
Try something like this
尝试这样的事情
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
回答by OfcOurSe
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:
也许现在回答这个问题有点晚了,但它可能对将来的某人有所帮助。我更喜欢在后台下载照片,使用 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
}
}
});