2017-01-04 39 views
0

我按照Retrofit頁面上的說明下載了一個圖像,但是沒有@Streaming標記,inputstream.read(buffer)會立即等於-1,渲染文件爲空。 (圖像很小,只有幾百kb) 即使當我使用@Streaming標記時,由於IllegalStateException,應用程序會繼續崩潰當我使用輸入流使用Retrofit返回空文件下載圖像

我試過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; 

} 
+1

爲什麼使用改造的圖像?改造是休息api客戶的不錯選擇,但對於圖像滑動或畢加索會更好。 –

+0

使用畢加索代替改造 – raj

+0

我將Glide用於我的項目。但是,我也想將圖像保存到內部存儲器(要使用Glide或Picasso,我需要在加載後保存緩存文件)。另外,我想弄清楚爲什麼這個代碼不起作用。我不知道我錯了哪裏 –

回答

2

試試這個,

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

還添加扶養;

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