okhttpclient文件下载
时间: 2024-10-25 11:11:47 浏览: 55
OkHttp是一个高效的HTTP客户端库,用于Android和Java平台,由Square开发。如果你想使用OkHttp进行文件下载,可以按照以下步骤操作:
1. 添加依赖:首先需要在项目中引入OkHttp的依赖,如果你使用的是Maven,可以在pom.xml中添加以下内容:
```xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.x.x</version> <!-- 更新到最新稳定版本 -->
</dependency>
```
2. 创建请求:创建一个OkHttpClient实例,并构造一个DownloadRequest,指定你要下载的URL和目标文件路径:
```java
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/file-to-download")
.build();
// 或者设置自定义连接超时、读取超时等配置
request.setRetryOnFailure(true);
request.setConnectTimeout(10, TimeUnit.SECONDS);
request.readTimeout(60, TimeUnit.SECONDS);
String filePath = "path/to/downloaded/file";
```
3. 开始下载:使用enqueue方法异步下载文件,回调里处理响应结果并保存文件:
```java
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 处理下载失败
Log.e("Download", "Failed to download", e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
try (ResponseBody body = response.body()) {
byte[] bytes = body.bytes();
Files.write(Paths.get(filePath), bytes);
// 如果有进度监听需求,可以使用ProgressListener
}
}
});
```
阅读全文