2015-10-01 65 views
9

私のアプリでRetrofitライブラリを使用して、すべての種類のファイル(バイナリ、イメージ、テキストなど)をダウンロードする必要があります。ネット上のすべての例はHTML GETメソッドを使用しています。自動キャッシングを防ぐためにPOSTを使用する必要があります。Retrofitライブラリを使ってAndroidにファイルをダウンロードする方法は?

私の質問は、RetrofitでPOSTメソッドを使用してファイルをダウンロードする方法ですか?

+0

はこれを試して...改造を使用して任意の種類のファイルをダウンロードするための次のコードを使用:http://stackoverflow.com/questions/32878478/how-to-download-file-in -android-using-retrofit-library/36682027#36682027 –

答えて

7

使用@Streaming

非同期

EDIT 1

//On your api interface 
@POST("path/to/your/resource") 
@Streaming 
void apiRequest(Callback<POJO> callback); 

restAdapter.apiRequest(new Callback<POJO>() { 
     @Override 
     public void success(POJO pojo, Response response) { 
      try { 
       //you can now get your file in the InputStream 
       InputStream is = response.getBody().in(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     @Override 
     public void failure(RetrofitError error) { 

     } 
    }); 

同期

//On your api interface 
@POST("path/to/your/resource") 
@Streaming 
Response apiRequest(); 

Response response = restAdapter.apiRequest(); 

try { 
    //you can now get your file in the InputStream 
    InputStream is = response.getBody().in(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

応答をありがとう、私はそれを試し、あなたに戻ってきます。 – Ehsan

+0

シンボルPOJOを解決できません。これを解決するには? – Ehsan

+0

これはオブジェクトクラスですが、それを 'Object'だけに変更することができます – NaviRamyle

2

Retrofit 2.0.0を使用している場合、answerを質問Use retrofit to download image fileで参照することができます。

キーポイントは、okhttp3.ReponseBodyを使用して生のバイナリデータを受信し、POJOは受信しません。

そして、あなたがファイルを取得するためにPOSTメソッドを使用したい、それだけで@POST@GETを変更するが、それはあなたのサーバがPOSTメソッドをサポートしているかどうかによって異なり、簡単です!

1

これはレトロフィット2

public interface ServerAPI { 
     @GET 
     Call<ResponseBody> downlload(@Url String fileUrl); 

     Retrofit retrofit = 
       new Retrofit.Builder() 
         .baseUrl("http://192.168.43.135/retro/") // REMEMBER TO END with/
         .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

} 

    //How To Call 
public void download(){ 
     ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class); 
     api.downlload("http://192.168.43.135/retro/pic.jpg").enqueue(new Callback<ResponseBody>() { 
        @Override 
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
         try { 
          File path = Environment.getExternalStorageDirectory(); 
          File file = new File(path, "file_name.jpg"); 
          FileOutputStream fileOutputStream = new FileOutputStream(file); 
          IOUtils.write(response.body().bytes(), fileOutputStream); 
         } 
         catch (Exception ex){ 
         } 
        } 

        @Override 
        public void onFailure(Call<ResponseBody> call, Throwable t) { 
        } 
       }); 
} 
+0

このコードはコンパイルされません。 'Interface'で物事を初期化することはできません。 –

+2

コンパイルしようとしましたか?それは私のために働く、これは私がどのように使用されている –

+0

私の悪い、あなたは正しい、私はKotlinに変換しました:) –

0

をファイルをダウンロードする方法では、MainActivity.javaで、次の機能を含める:画像ダウンロードの一部を扱う

void getRetrofitImage() { 

    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(url) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

    RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class); 

    Call<ResponseBody> call = service.getImageDetails(); 

    call.enqueue(new Callback<ResponseBody>() { 
     @Override 
     public void onResponse(Response<ResponseBody> response, Retrofit retrofit) { 

      try { 

       Log.d("onResponse", "Response came from server"); 

       boolean FileDownloaded = DownloadImage(response.body()); 

       Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded); 

      } catch (Exception e) { 
       Log.d("onResponse", "There is an error"); 
       e.printStackTrace(); 
      } 

     } 

     @Override 
     public void onFailure(Throwable t) { 
      Log.d("onFailure", t.toString()); 
     } 
    }); 
} 

ファイルは次のようになります。

private boolean DownloadImage(ResponseBody body) { 

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

     try { 
      in = body.byteStream(); 
      out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg"); 
      int c; 

      while ((c = in.read()) != -1) { 
       out.write(c); 
      } 
     } 
     catch (IOException e) { 
      Log.d("DownloadImage",e.toString()); 
      return false; 
     } 
     finally { 
      if (in != null) { 
       in.close(); 
      } 
      if (out != null) { 
       out.close(); 
      } 
     } 

     int width, height; 
     ImageView image = (ImageView) findViewById(R.id.imageViewId); 
     Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg"); 
     width = 2*bMap.getWidth(); 
     height = 6*bMap.getHeight(); 
     Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false); 
     image.setImageBitmap(bMap2); 

     return true; 

    } catch (IOException e) { 
     Log.d("DownloadImage",e.toString()); 
     return false; 
    } 
} 

完全なチュートリアルでこれを見ることができます:Image Download using Retrofit 2.0

0

私は

File file = new File("Your_File_path/name"); 

    private void startDownload() { 

    if (!NetWorkUtils.getInstance(context).isNetworkAvailable()) { 
     Toast.makeText(context, "No data connection available", Toast.LENGTH_SHORT).show(); 
     return; 
    } 

    showProgressDialog(); 

    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(FILE_BASE_URL) 
      .build(); 

    FileHandlerService handlerService = retrofit.create(FileHandlerService.class); 

    Call<ResponseBody> call = handlerService.downloadFile(mFileName); 
    call.enqueue(new Callback<ResponseBody>() { 
     @Override 
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
      dismissProgressDialog(); 
      if (response.isSuccessful()) { 
       if (writeResponseBodyToDisk(response.body())) { 
        listener.onFileLoaded(file); 
       } 
      } else { 
       listener.onDownloadFailed("Resource not Found"); 
      } 
     } 

     @Override 
     public void onFailure(Call<ResponseBody> call, Throwable t) { 
      dismissProgressDialog(); 
      listener.onDownloadFailed("Download Failed"); 
      t.printStackTrace(); 
     } 
    }); 

} 


interface FileHandlerService { 

    @GET("uploads/documents/{file_name}") 
    Call<ResponseBody> downloadFile(
      @Path("file_name") String imageName); 
} 

private boolean writeResponseBodyToDisk(ResponseBody body) { 
    try { 

     InputStream inputStream = null; 
     OutputStream outputStream = null; 

     try { 
      byte[] fileReader = new byte[4096]; 

      long fileSize = body.contentLength(); 
      long fileSizeDownloaded = 0; 

      inputStream = body.byteStream(); 
      outputStream = new FileOutputStream(file); 

      while (true) { 
       int read = inputStream.read(fileReader); 

       if (read == -1) { 
        break; 
       } 

       outputStream.write(fileReader, 0, read); 

       fileSizeDownloaded += read; 

       Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize); 
      } 

      outputStream.flush(); 

      return true; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return false; 
     } finally { 
      if (inputStream != null) { 
       inputStream.close(); 
      } 
      if (outputStream != null) { 
       outputStream.close(); 
      } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 
+0

それは私のアンドロイド5.1で動作しますが、他にはありません。私はアンドロイド6でそれをテストして動作しません0 – Rodrigo

関連する問題