okhttp3实现下载进度条
时间: 2023-09-02 14:12:09 浏览: 88
以下是使用OkHttp3实现下载进度条的示例:
1. 引入依赖
在项目的build.gradle文件中添加OkHttp3依赖:
```groovy
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}
```
2. 创建OkHttpClient
```java
OkHttpClient client = new OkHttpClient();
```
3. 创建Request
```java
Request request = new Request.Builder()
.url("http://www.example.com/file.txt")
.build();
```
4. 执行请求
```java
Call call = client.newCall(request);
Response response = call.execute();
```
5. 获取响应体并写入文件
```java
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
FileOutputStream outputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
6. 获取下载进度并更新UI
```java
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
FileOutputStream outputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
long total = response.body().contentLength();
long sum = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
// 更新UI
updateProgress(progress);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
其中,updateProgress方法用于更新下载进度的UI。
阅读全文