Java 使用Refught2/okhttp3上载文件,上载操作始终执行两次,一次快速,另一次慢速
我使用ProgressRequestBody来显示上载操作的进度Java 使用Refught2/okhttp3上载文件,上载操作始终执行两次,一次快速,另一次慢速,java,okhttp,retrofit2,Java,Okhttp,Retrofit2,我使用ProgressRequestBody来显示上载操作的进度 @Override public void writeTo(BufferedSink sink) throws IOException { // see https://github.com/square/okhttp/issues/1587 // JakeWharton commented on 28 Apr 2015 's answer final BufferedSink progressSink
@Override
public void writeTo(BufferedSink sink) throws IOException {
// see https://github.com/square/okhttp/issues/1587
// JakeWharton commented on 28 Apr 2015 's answer
final BufferedSink progressSink = Okio.buffer(new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
mListener.onProgressUpdate(bytesWritten,contentLength,bytesWritten == contentLength);
System.out.println("--byte--"+bytesWritten);
super.write(source, byteCount);
}
});
requestBody.writeTo(progressSink);
System.out.println("--byte-- start---");
progressSink.flush();
System.out.println("--byte-- end---");
}
每次执行上载操作时,都会调用两次此方法。
起初,我认为问题可能是添加到okhttpclient for log中的拦截器,但事实并非如此。谁能帮我?谢谢
更多代码:
public interface UploadInterface {
@Multipart
@POST("path")
Call<JsonBase<Result>> uploadFile(
@Query("_appTicket") String cookie,
@Query("Id") String id,
@Part MultipartBody.Part requestBody
);
}
公共接口上传接口{
@多部分
@帖子(“路径”)
调用上传文件(
@查询(“\u appTicket”)字符串cookie,
@查询(“Id”)字符串Id,
@Part MultipartBody.Part requestBody
);
}
上载操作:
final ProgressRequestBody progressRequestBody
= new ProgressRequestBody(
RequestBody.create(
MediaType.parse("multipart/form-data"),
tempZip
)
);
MultipartBody.Part part = MultipartBody.Part
.createFormData("file","upload",progressRequestBody);
final Call<JsonBase<JsonUploadResult>> call
= uplocaInterface.uploadFile(cookie,s,part);
final ProgressRequestBody ProgressRequestBody
=新ProgressRequestBody(
RequestBody.create(
parse(“多部分/表单数据”),
坦普齐普
)
);
MultipartBody.Part部分=MultipartBody.Part
.createFormData(“文件”、“上载”、progressRequestBody);
最后的电话
=uplocaInterface.uploadFile(cookie、s、part);
您好,请查看下面的博客文章
它用示例很好地解释了您的问题。我使用此代码跟踪http请求进度
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
long total = 0;
long read;
Handler handler = new Handler(Looper.getMainLooper());
while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
total += read;
sink.flush();
final int percent = (int) (total / (float)file.length() * 100);
handler.post(new Runnable() {
@Override
public void run() {
listener.transferred(percent);
}
});
}
} finally {
Util.closeQuietly(source);
}
}
删除所有http客户端拦截器以避免方法调用两次。似乎您正在使用HttpLoggingInterceptor,它为请求主体调用writeTo。您可以忽略这个问题,因为HttpLoggingInterceptor应该在发布版本中被禁用,或者覆盖HttpLoggingInterceptor的拦截方法,并在这个特定的上传请求中禁用它。谢谢@Hendi remove http inteceptors,它非常适合我。救了我一天。