如何在OkHttp 3中跟踪上传进度 我可以找到v2但不是v3的答案,例如this
来自OkHttp食谱的样本Multipart请求
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
答案 0 :(得分:12)
你可以装饰你的OkHttp请求体来计算写入时写入的字节数;为了完成这项任务,请使用Listener和Voila的实例将您的MultiPart RequestBody包装在此RequestBody中!
public class ProgressRequestBody extends RequestBody {
protected RequestBody mDelegate;
protected Listener mListener;
protected CountingSink mCountingSink;
public ProgressRequestBody(RequestBody delegate, Listener listener) {
mDelegate = delegate;
mListener = listener;
}
@Override
public MediaType contentType() {
return mDelegate.contentType();
}
@Override
public long contentLength() {
try {
return mDelegate.contentLength();
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
mCountingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(mCountingSink);
mDelegate.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink {
private long bytesWritten = 0;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
bytesWritten += byteCount;
mListener.onProgress((int) (100F * bytesWritten / contentLength()));
}
}
public interface Listener {
void onProgress(int progress);
}
}
查看this link了解更多信息。
答案 1 :(得分:2)
我无法获得任何对我有用的答案。问题在于,在上传图像之前,进度将达到100%,暗示在通过有线发送数据之前已填充了一些缓冲区。经过研究,我发现确实如此,该缓冲区就是Socket发送缓冲区。向OkHttpClient提供SocketFactory终于可以了。我的Kotlin代码如下...
首先,和其他人一样,我有一个CountingRequestBody用来包装MultipartBody。
IndexError
我在Retrofit2中使用它。一般用法如下:
class CountingRequestBody(var delegate: RequestBody, private var listener: (max: Long, value: Long) -> Unit): RequestBody() {
override fun contentType(): MediaType? {
return delegate.contentType()
}
override fun contentLength(): Long {
try {
return delegate.contentLength()
} catch (e: IOException) {
e.printStackTrace()
}
return -1
}
override fun writeTo(sink: BufferedSink) {
val countingSink = CountingSink(sink)
val bufferedSink = Okio.buffer(countingSink)
delegate.writeTo(bufferedSink)
bufferedSink.flush()
}
inner class CountingSink(delegate: Sink): ForwardingSink(delegate) {
private var bytesWritten: Long = 0
override fun write(source: Buffer, byteCount: Long) {
super.write(source, byteCount)
bytesWritten += byteCount
listener(contentLength(), bytesWritten)
}
}
}
在这一点上,我正在取得进步,但是在上传数据时,我会看到100%,然后等待很长时间。关键是,在我的设置中,默认情况下已将套接字配置为缓冲3145728字节的发送数据。好吧,我的图像就在那之下,进度显示了填充该套接字发送缓冲区的进度。为了减轻这种情况,请为OkHttpClient创建一个SocketFactory。
val builder = MultipartBody.Builder()
// Add stuff to the MultipartBody via the Builder
val body = CountingRequestBody(builder.build()) { max, value ->
// Progress your progress, or send it somewhere else.
}
然后在配置过程中进行设置。
class ProgressFriendlySocketFactory(private val sendBufferSize: Int = DEFAULT_BUFFER_SIZE) : SocketFactory() {
override fun createSocket(): Socket {
return setSendBufferSize(Socket())
}
override fun createSocket(host: String, port: Int): Socket {
return setSendBufferSize(Socket(host, port))
}
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket {
return setSendBufferSize(Socket(host, port, localHost, localPort))
}
override fun createSocket(host: InetAddress, port: Int): Socket {
return setSendBufferSize(Socket(host, port))
}
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket {
return setSendBufferSize(Socket(address, port, localAddress, localPort))
}
private fun setSendBufferSize(socket: Socket): Socket {
socket.sendBufferSize = sendBufferSize
return socket
}
companion object {
const val DEFAULT_BUFFER_SIZE = 2048
}
}
正如其他人所提到的,记录请求正文可能会影响此过程,并导致多次读取数据。要么不记录正文,要么我为CountingRequestBody关闭它。为此,我编写了自己的HttpLoggingInterceptor,它解决了此问题和其他问题(例如记录MultipartBody)。但这超出了这个问题的范围。
val clientBuilder = OkHttpClient.Builder()
.socketFactory(ProgressFriendlySocketFactory())
其他问题与MockWebServer有关。我有使用MockWebServer和json文件的功能,因此我的应用程序可以在没有网络的情况下运行,因此我可以在没有负担的情况下进行测试。为了使此代码起作用,分派器需要读取主体数据。我创建了这个Dispatcher就是为了做到这一点。然后它将分派转发到另一个分派器,例如默认的QueueDispatcher。
if(requestBody is CountingRequestBody) {
// don't log the body in production
}
您可以在MockWebServer中将其用作:
class BodyReadingDispatcher(val child: Dispatcher): Dispatcher() {
override fun dispatch(request: RecordedRequest?): MockResponse {
val body = request?.body
if(body != null) {
val sink = ByteArray(1024)
while(body.read(sink) >= 0) {
Thread.sleep(50) // change this time to work for you
}
}
val response = child.dispatch(request)
return response
}
}
这是我项目中所有有效的代码。我确实将其出于说明目的。如果开箱即用对您不起作用,我深表歉意。
答案 2 :(得分:0)
根据Sourabh的回答,我想告诉CountingSink的那个领域
private long bytesWritten = 0;
必须将移入ProgressRequestBody类
答案 3 :(得分:0)
不幸的是,以上代码无法解决我的问题。这段代码对我有用:
// TODO: Build a request body
RequestBody body = null;
// Decorate the request body to keep track of the upload progress
CountingRequestBody countingBody = new CountingRequestBody(body,
new CountingRequestBody.Listener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength) {
float percentage = 100f * bytesWritten / contentLength;
// TODO: Do something useful with the values
}
});
// TODO: Build a request using the decorated body