[Android開発ネタ] Retrofitを使用し、ファイルをダウンロードする

Interface用意して、ResponceBodyからByte配列取得してモゴモゴする。

Retrofit使ってても実態はOkHttp。

スポンサーリンク

Interface

//
@GET
Observable<ResponseBody> downloadFile(@Url String fileUrl);

API接続クラス

//
public class DownloadFileApi {

    private String url;

    private Observer<ResponseBody> callBack;

    public DownloadFileApi (String url, Observer<ResponseBody> callBack) {
        this.url = url;
        this.callBack = callBack;
    }

    public void call() {

        Observable<ResponseBody> api = ApiManager.get()
                .getApiCall(AppServiceApi.class)
                .downloadFile(url);

        api.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callBack);
    }
}

呼び出し、及び、保存

//
    private void downloadFile(final String filePath) {

        DownloadFileApi api = new DownloadFileApi(filePath, new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseBody value) {
                String fileName = new File(filePath).getName();
                boolean ret = saveFile(value, fileName);
            }

            @Override
            public void onError(Throwable e) {}

            @Override
            public void onComplete() {}
        });
        api.onExecute();

    }

   private boolean saveFile(ResponseBody body, String fileName) {

        try {
            File writeFile = new File(getSavePath() + File.separator + fileName);

            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(writeFile);

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

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

                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                }

                outputStream.flush();

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

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    private String getSavePath() {
        File file = new File(getFilesDir().toString() + File.separator + "file");
        if (!file.exists()) {
            boolean success = file.mkdirs();
        }
        return file.toString();
    }
タイトルとURLをコピーしました