okhttp上传并且显示进度
本帖最后由 Genius 于 2017-2-15 11:01 编辑okhttp非常好的一个http请求框架,可惜上传没有提供上传进度,需要自定义RequestBody才能实现。网上有很多的文章表示都是差不多。自定义RequestBoyd代码如下:
private RequestBody createUploadFileRequestBody(final MediaType mediaType,
finalFile file,
final IProgressListener iProgressListener) {
return new RequestBody() {
@Override
public MediaType contentType() {
return mediaType;
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source;
try {
source = Okio.source(file);
Buffer buffer = new Buffer();
long conentLength = contentLength();
long length = -1;
long bufferSize = 1024 * 1024;
long progress = 0;
while ((length = source.read(buffer, bufferSize)) != -1) {
sink.write(buffer, length);
progress += length;
iProgressListener.onProgress(conentLength,
progress, (progress == conentLength));
}
sink.flush();
source.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
监听下载进度的接口
public interface IProgressListener {
/**
* 上传,下载 进度的监听
* @param contentLength 文件的大小
* @param progress进度
* @param isDone 是否完成
*/
void onProgress(long contentLength, long progress, boolean isDone);
/**
* 错误接口
* @param requestUrl 请求的url
* @param errorMsg 错误的信息
*/
void onFailure(String requestUrl, String errorMsg);
}
使用方法
RequestBody uploadFileRequestBody = createUploadFileRequestBody(MultipartBody.<font color="#660e7a"><i>FORM</i></font>,
uploadFile, iProgressListener);
Request uploadRequest = <font color="#000080">new </font>Request.Builder()
.url(uploadHttpUrl)
.post(uploadRequestBody)
.build();
<font color="#660e7a">mOkHttpClient</font>.newCall(uploadRequest).enqueue(<font color="#000080">new </font>Callback() {
<font color="#808000">@Override
</font><font color="#808000"> </font><font color="#000080">public void </font>onFailure(Call call, IOException e) {
System.<font color="#660e7a"><i>out</i></font>.println(<font color="#008000">"onFailure: " </font>+ e.getMessage());
}
<font color="#808000">@Override
</font><font color="#808000"> </font><font color="#000080">public void </font>onResponse(Call call, Response response) <font color="#000080">throws </font>IOException {
System.<font color="#660e7a"><i>out</i></font>.println(<font color="#008000">"onResponse code: " </font>+ response.code());
<font color="#000080">if </font>(response.isSuccessful()) {
System.<font color="#660e7a"><i>out</i></font>.println(<font color="#008000">"onResponse: " </font>+ response.body().string());
}
call.cancel();
}
});
页:
[1]