2017-01-04 5 views
0

Retrofitページの指示に従って画像をダウンロードしますが、@ Streamingタグを使用しないと、inputstream.read(buffer)は直ちに-1になり、ファイルは空になります。 (画像は非常に小さく、わずか数百kbです) IlStreamStateExceptionのために入力ストリームを使用すると、@Streamingタグを使用してもアプリケーションがクラッシュする場合があります。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

画像にレトロフィットを使用する理由は何ですか? Retrofitは残りの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' 
関連する問題