okhttp下载文件断点下载暂停下载
时间: 2023-12-10 21:35:52 浏览: 61
以下是使用OkHttp实现文件下载的示例代码,其中包括断点下载和暂停下载的功能:
```java
public class DownloadManager {
private static final String TAG = "DownloadManager";
private static final int DEFAULT_TIMEOUT = 10;
private static DownloadManager mInstance;
private OkHttpClient mOkHttpClient;
private Handler mHandler;
private DownloadManager() {
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
mHandler = new Handler(Looper.getMainLooper());
}
public static DownloadManager getInstance() {
if (mInstance == null) {
synchronized (DownloadManager.class) {
if (mInstance == null) {
mInstance = new DownloadManager();
}
}
}
return mInstance;
}
public void download(final String url, final String destFileDir, final DownloadListener listener) {
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handleError(call, e, listener);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
handleResponse(response, destFileDir, listener);
} else {
handleError(call, new IOException("Unexpected code " + response), listener);
}
}
});
}
private void handleResponse(Response response, String destFileDir, DownloadListener listener) {
InputStream is = null;
byte[] buf = new byte[2048];
int len;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
final long total = response.body().contentLength();
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, getFileName(response));
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
final long finalSum = sum;
mHandler.post(new Runnable() {
@Override
public void run() {
listener.onProgress(finalSum * 1.0f / total);
}
});
}
fos.flush();
mHandler.post(new Runnable() {
@Override
public void run() {
listener.onSuccess();
}
});
} catch (Exception e) {
handleError(response.request().call(), e, listener);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
}
}
}
private void handleError(final Call call, final Exception e, final DownloadListener listener) {
mHandler.post(new Runnable() {
@Override
public void run() {
listener.onFailure(e);
}
});
if (call != null) {
call.cancel();
}
}
private String getFileName(Response response) {
String fileName = "";
String disposition = response.header("Content-Disposition");
if (!TextUtils.isEmpty(disposition)) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
}
if (TextUtils.isEmpty(fileName)) {
fileName = System.currentTimeMillis() + ".apk";
}
return fileName;
}
public interface DownloadListener {
void onProgress(float progress);
void onSuccess();
void onFailure(Exception e);
}
}
```
使用示例:
```java
DownloadManager.getInstance().download(url, destFileDir, new DownloadManager.DownloadListener() {
@Override
public void onProgress(float progress) {
// 更新进度条
}
@Override
public void onSuccess() {
// 下载成功
}
@Override
public void onFailure(Exception e) {
// 下载失败
}
});
```
暂停下载可以通过调用`Call.cancel()`方法实现,断点下载可以通过在请求头中添加`Range`字段实现。相关代码如下:
```java
public void download(final String url, final String destFileDir, final DownloadListener listener) {
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handleError(call, e, listener);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
handleResponse(response, destFileDir, listener);
} else {
handleError(call, new IOException("Unexpected code " + response), listener);
}
}
});
}
public void pause(Call call) {
if (call != null) {
call.cancel();
}
}
public void resume(final String url, final String destFileDir, final DownloadListener listener) {
final File file = new File(destFileDir, getFileName(url));
final long currentLength = file.length();
final Request request = new Request.Builder()
.url(url)
.addHeader("RANGE", "bytes=" + currentLength + "-")
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handleError(call, e, listener);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
handleResponse(response, file.getAbsolutePath(), listener);
} else {
handleError(call, new IOException("Unexpected code " + response), listener);
}
}
});
}
```
相关问题: