使用Retrofit下载空文件下载图像

时间:2017-01-04 09:25:50

标签: java android retrofit

我按照Retrofit页面上的说明下载图像,但是,如果没有@Streaming标记,inputstream.read(缓冲区)将立即等于-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;

}

1 个答案:

答案 0 :(得分:2)

试试这个,

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

还添加了依赖性;

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