包的版本号如下
compile'com.squareup.retrofit2:retrofit:2.3.0'
compile'com.squareup.retrofit2:retrofit-adapters:2.3.0'
compile'com.squareup.retrofit2:converter-gson:2.3.0'
compile'com.squareup.retrofit2:converter-scalars:2.3.0'
compile'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile'com.squareup.okhttp3:logging-interceptor:3.8.0'
加入日志拦截器后上传文件时会重复写入两次文件导致上传进度错乱。去掉后能够正常使用。这是个巨坑我花了一天多的时间一直没调试出是什么地方引起的,绝望之下把日志输出注释了,然后一切就好了==!
我是采用重写RequestBody的方式来实现进度监听的
public final classFileRequestBody extends RequestBody {
privateRequestBodymRequestBody;
privateProgressListenermProgressListener;
privateBufferedSinkbufferedSink;
//每个RequestBody对应一个tag,存放在map中,保证计算的时候不会出现重复
privateStringtag;
publicFileRequestBody(File file,ProgressListener progressListener,String tag) {
this.mRequestBody= RequestBody.create(MediaType.parse("multipart/form-data"),file);
this.mProgressListener= progressListener;
this.tag= tag;
}
//其实只是添加一个回调和tag标识,实际起作用的还是requestBody
publicFileRequestBody(RequestBody requestBody,ProgressListener progressListener,String tag) {
this.mRequestBody= requestBody;
this.mProgressListener= progressListener;
this.tag= tag;
}
//返回了requestBody的类型,想什么form-data/MP3/MP4/png等等等格式
@Override
publicMediaTypecontentType() {
returnmRequestBody.contentType();
}
//返回了本RequestBody的长度,也就是上传的totalLength
@Override
public longcontentLength()throwsIOException {
returnmRequestBody.contentLength();
}
@Override
public voidwriteTo(BufferedSink sink)throwsIOException {
//包装
bufferedSink= Okio.buffer(newCountingSink(sink));
//写入
mRequestBody.writeTo(bufferedSink);
//必须调用flush,否则最后一部分数据可能不会被写入
bufferedSink.flush();
}
longoldTime=0l;
protected final classCountingSinkextendsForwardingSink {
publicCountingSink(Sink delegate) {
super(delegate);
}
longbytesWritten=0L;
//总字节长度,避免多次调用contentLength()方法
longcontentLength=0L;
@Override
public voidwrite(Buffer source, longbyteCount)throwsIOException {
super.write(source,byteCount);
if(contentLength==0) {
//获得contentLength的值,后续不再调用
contentLength= contentLength();
}
//增加当前写入的字节数
bytesWritten+= byteCount;
mProgressListener.onProgress((int) ((double)bytesWritten/ (double)contentLength) *100,tag);
mProgressListener.onDetailProgress(bytesWritten,contentLength,tag);
}
}
}