版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Retrofit下载文件
第一步,请求接口
//下载图片
@Streaming
@GET
Call<ResponseBody> downloadPicWithUrl(@Url String url);
第二步,请求网络
/**
* 保存图片
*
* @param baseUrl
* @param urlpic
*/
private void downFileWithPic(String baseUrl, final String urlpic, final int type) {
OkHttpClient builder = new OkHttpClient.Builder().build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(builder)
.build();
final HttpPostService fileDownloadApi = retrofit.create(HttpPostService.class);
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
Response<ResponseBody> response = fileDownloadApi.downloadPicWithUrl(urlpic).execute();
if (response != null && response.isSuccessful()) {
//文件总长度
long fileSize = response.body().contentLength();
long fileSizeDownloaded = 0;
InputStream is = response.body().byteStream();
if (AppUtil.isExitsSdcard()) {
// 首先保存图片
File file = Environment.getExternalStorageDirectory().getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
String fileName = "picture";
File appDir = new File(file, fileName);
if (!appDir.exists()) {
appDir.mkdirs();
}
String filePicName = null;
int indexOf = urlpic.lastIndexOf(".");
String picName = urlpic.substring(0, indexOf);
// LogUtil.e("picname"+picName);
if (type == 1) {
filePicName = picName + ".jpg";
} else {
filePicName = picName + ".gif";
}
File filePic = new File(appDir, filePicName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePic);
int count = 0;
byte[] buffer = new byte[1024];
while ((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
fileSizeDownloaded += count;
// subscriber.onNext("file download: " + fileSizeDownloaded + " of " + fileSize);
}
fos.flush();
fos.close();
subscriber.onCompleted();
} catch (Exception e) {
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePic.getAbsolutePath()))));
ToastUtil.showSafeToast("保存成功");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
})
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
Log.e("MainActivity", "文件下载完成");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
//Log.e("onNext", s);
}
});
}