gpt4 book ai didi

java - 使用 Retrofit 下载图像返回空文件

转载 作者:行者123 更新时间:2023-12-02 03:08:01 25 4
gpt4 key购买 nike

我按照Retrofit页面上的说明下载图像,但是,如果没有@Streaming标记,inputstream.read(buffer)将立即等于-1,使文件呈现为空。 (图片很小,只有几百kb)即使我使用@Streaming标签,当我使用输入流时,由于IllegalStateException,应用程序也会不断崩溃

我尝试了 HttpConnection,并且可以很好地下载图像。但是,我真的想让它与 Retrofit 一起使用

public static String downloadImage(String bearer, long pictureId,Context context){
String path = "";
NetworkAPI apiService = NetworkClient.getClient().create(NetworkAPI.class);
//Call<ResponseBody> downloadCall = apiService.downloadImage(bearer,pictureId);
Call<ResponseBody> downloadCall = apiService.downloadFileWithDynamicUrlSync("https://androidtutorialpoint.com/api/RetrofitAndroidImageResponse");

try {
Response<ResponseBody> response = downloadCall.execute();
if(response.isSuccessful()) {

Log.d(TAG, "success download" + response.body().string());

Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
OutputStream out = null;

try {
in = response.body().byteStream();


File file = PictureUtil.createImageFile(context);

Uri photoURI = FileProvider.getUriForFile(context,
"vn.com.wk.bradleyaudit.fileprovider",
file);

out = new FileOutputStream(file);


long fileSize = response.body().contentLength();
long downloadedSize = 0;

Log.d("DownloadImage", "size"+fileSize);
byte[] buffer = new byte[4096];

while (true) {
int bufferLength = in.read(buffer);
Log.d("DownloadImage", "buffer Length"+bufferLength);

if (bufferLength == -1) {
break;
}
out.write(bufferLength);
out.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;

}

out.flush();
path = photoURI.toString();
Log.d("DownloadImage", "path"+path);
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}

}

}

} catch (IOException e) {
e.printStackTrace();
}

return path;

}

最佳答案

试试这个,

 Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

同时添加依赖;

compile 'com.squareup.picasso:picasso:2.5.2'

关于java - 使用 Retrofit 下载图像返回空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41460254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com