1 首先要在app/build.gradle中添加依赖,另外注意清单文件中打开相应网络访问权限如:
implementation 'com.squareup.okhttp3:okhttp:3.14.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.14.1'
implementation 'com.squareup.okio:okio:1.6.0'
2 创建一个OkHttpclient
OkHttpClient okHttpClient = new OkHttpClient();
3 创建Request
Request request = new Request.Builder()
.url(url)
.addHeader("Connection", "close") //这里不设置可能产生EOF错误
.build();
4 获取下载进度
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
LogUtil.e(TAG,"download progress : " + progress);
mView.onDownloading("",progress);
}
fos.flush();
5 附完整代码
public void downloadFile() {
final String url = "http://127.0.0.1:8080/park/map/download/test.mp3";
final long startTime = System.currentTimeMillis();
LogUtil.i(TAG,"startTime="+startTime);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.addHeader("Connection", "close")
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
LogUtil.i(TAG,"download failed");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mapdata/download";
if(!FileUtils.isFolderExists(savePath)){
FileUtils.makeDirectory(savePath);
}
try {
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
LogUtil.e(TAG,"download progress : " + progress);
mView.onDownloading("",progress);
}
fos.flush();
LogUtil.e(TAG,"download success");
LogUtil.e(TAG,"totalTime="+ (System.currentTimeMillis() - startTime));
} catch (Exception e) {
e.printStackTrace();
LogUtil.e(TAG,"download failed : "+e.getMessage());
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}