OkHttp实现MediaType为空带进度条上传文件
时间: 2024-02-27 11:51:35 浏览: 79
好的,对于这个问题,我可以给出以下的代码示例:
```java
private void uploadFileWithProgress(String url, File file, final MediaType mediaType, final ProgressListener progressListener) {
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder requestBuilder = originalRequest.newBuilder()
.method(originalRequest.method(), new ProgressRequestBody(originalRequest.body(), progressListener));
return chain.proceed(requestBuilder.build());
}
})
.build();
RequestBody requestBody = RequestBody.create(mediaType, file);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
// 处理响应结果
} catch (IOException e) {
e.printStackTrace();
}
}
```
其中,`ProgressRequestBody` 是一个自定义的 `RequestBody`,用于在上传文件时监听上传进度。它的代码实现如下:
```java
public class ProgressRequestBody extends RequestBody {
private RequestBody requestBody;
private ProgressListener progressListener;
private CountingSink countingSink;
public ProgressRequestBody(RequestBody requestBody, ProgressListener progressListener) {
this.requestBody = requestBody;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
try {
return requestBody.contentLength();
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
countingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(countingSink);
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private final class CountingSink extends ForwardingSink {
private long totalBytesWritten = 0L;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
totalBytesWritten += byteCount;
progressListener.onProgress(totalBytesWritten, contentLength());
}
}
}
```
然后,在调用 `uploadFileWithProgress` 方法时,只需要传入文件、媒体类型、进度监听器等参数即可:
```java
uploadFileWithProgress(url, file, MediaType.parse("image/png"), new ProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength) {
// 更新进度条
}
});
```
注意,这里的 `MediaType` 必须要正确指定,否则可能会导致上传失败。另外,由于上传文件是一个比较耗时的操作,建议在子线程中执行。
阅读全文