如何在android 使用okhttp实现带进度的文件上传
时间: 2024-03-02 09:49:27 浏览: 216
android中实现OkHttp下载文件并带进度条
5星 · 资源好评率100%
要在 Android 中使用 OkHttp 实现带进度的文件上传,可以使用 OkHttp 提供的 Interceptor 和 RequestBody 类。下面是一个简单的示例代码:
```java
public class ProgressRequestBody extends RequestBody {
private static final int DEFAULT_BUFFER_SIZE = 2048;
private final File file;
private final String contentType;
private final ProgressListener listener;
public ProgressRequestBody(File file, String contentType, ProgressListener listener) {
this.file = file;
this.contentType = contentType;
this.listener = listener;
}
@Override
public MediaType contentType() {
return MediaType.parse(contentType);
}
@Override
public long contentLength() {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = file.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long uploaded = 0;
try (InputStream in = new FileInputStream(file)) {
int read;
while ((read = in.read(buffer)) != -1) {
uploaded += read;
sink.write(buffer, 0, read);
if (listener != null) {
listener.onProgress(uploaded, fileLength);
}
}
}
}
public interface ProgressListener {
void onProgress(long uploaded, long total);
}
}
```
这个类继承自 OkHttp 的 RequestBody 类,并实现了上传文件进度监听。在 writeTo() 方法中使用 InputStream 从文件中读取数据,并将数据写入 BufferedSink 中。同时,每次写入数据都会调用 onProgress() 方法通知进度监听器。
然后,创建一个 OkHttpClient,添加一个 Interceptor,该 Interceptor 使用 ProgressRequestBody 替换 RequestBody,从而实现进度监听:
```java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// 使用 ProgressRequestBody 替换 RequestBody
ProgressRequestBody requestBody = new ProgressRequestBody(file, contentType, listener);
Request request = original.newBuilder()
.method(original.method(), requestBody)
.build();
return chain.proceed(request);
}
})
.build();
```
其中,file 是要上传的文件,contentType 是文件的 MIME 类型,listener 是进度监听器。最后,使用 OkHttpClient 发起一个上传文件的 Request:
```java
Request request = new Request.Builder()
.url(uploadUrl)
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 上传失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 上传成功
}
});
```
在 onResponse() 方法中处理上传结果即可。
阅读全文