下载带有改装的图像返回空文件

9nvpjoqh  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(368)

我按照改装页面上的说明下载了一个图像,但是,如果没有@streaming标记,inputstream.read(buffer)将立即等于-1,从而导致文件为空(图像非常小,只有几百kb)即使我使用@streaming标记,当我使用inputstream时,由于illegalstateexception,应用程序也会不断崩溃
我尝试了httpconnection,可以很好地下载图像。不过,我真的很想让它与改造工作

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;

}
pjngdqdw

pjngdqdw1#

试试这个,

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

还增加了依赖性;

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

相关问题