1 首先要在app/build.gradle中添加依賴祝迂,另外注意清單文件中打開相應(yīng)網(wǎng)絡(luò)訪問權(quán)限如:
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 創(chuàng)建一個OkHttpclient
OkHttpClient okHttpClient = new OkHttpClient();
3 創(chuàng)建Request
Request request = new Request.Builder()
.url(url)
.addHeader("Connection", "close") //這里不設(shè)置可能產(chǎn)生EOF錯誤
.build();
4 獲取下載進(jìn)度
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) {
}
}
}
});
}