Android OKHTTP 3跟踪多部分上载进度

Android OKHTTP 3跟踪多部分上载进度,android,okhttp3,Android,Okhttp3,如何在OkHttp 3中跟踪上传进度 我可以找到v2的答案,但不能找到v3的答案,比如 来自OkHttp recipes的示例多部分请求 private static final String IMGUR_CLIENT_ID = "..."; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private final OkHttpClient client = new OkHttpCli

如何在OkHttp 3中跟踪上传进度 我可以找到v2的答案,但不能找到v3的答案,比如

来自OkHttp recipes的示例多部分请求

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());
}

您可以装饰您的OkHttp请求主体,以计算写入时写入的字节数;为了完成这项任务,请使用Listener和Voila实例将多部分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);
    }
}

查看更多信息。

根据苏拉布的回答,我想告诉你CountingSink的字段

private long bytesWritten = 0;

必须移动到ProgressRequestBody类中

我无法获得任何对我有用的答案。问题是,在上传图像之前,进度将达到100%,这意味着在通过网络发送数据之前,某些缓冲区已被填满。经过一些研究,我发现情况确实如此,缓冲区就是套接字发送缓冲区。为OkHttpClient提供SocketFactory最终奏效了。我的Kotlin代码如下

首先,和其他人一样,我有一个CountingRequestBody,用于包装MultipartBody

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)
        }
    }
}
我在改型2中使用这个。一般用法如下:

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.
}
在这一点上,我正在取得进展,但我会看到100%,然后在上传数据时等待很长时间。关键是,在我的设置中,默认情况下,套接字配置为缓冲发送数据的3145728字节。我的图片就在下面,进度显示了填充套接字发送缓冲区的进度。为了缓解这种情况,请为OkHttpClient创建一个SocketFactory

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
    }
}
在配置期间,设置它

val clientBuilder = OkHttpClient.Builder()
    .socketFactory(ProgressFriendlySocketFactory())
正如其他人提到的,记录请求主体可能会影响这一点,并导致数据被多次读取。要么不记录正文,要么我所做的就是将其关闭用于CountingRequestBody。为此,我编写了自己的HttpLoggingInterceptor,它解决了这个问题和其他问题(比如记录多部分体)。但这超出了这个问题的范围

if(requestBody is CountingRequestBody) {
  // don't log the body in production
}
其他问题是MockWebServer。我有一种使用MockWebServer和json文件的风格,这样我的应用程序就可以在没有网络的情况下运行,这样我就可以在没有负担的情况下进行测试。为了使该代码正常工作,调度器需要读取主体数据。我创建这个调度器就是为了实现这一点。然后它将调度转发给另一个调度程序,如默认的QueueDispatcher

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
    }
}
您可以在MockWebServer中将其用作:

var server = MockWebServer()
server.setDispatcher(BodyReadingDispatcher(QueueDispatcher()))

这是我项目中所有的工作代码。我确实是出于说明的目的把它拔出来的。如果开箱即用对您不起作用,我道歉。

OkHttp3
样本中有一个配方。它显示了如何显示下载进度。如果您仔细查看,可能会创建一个上载进度监视器。在这里找到它为什么,当它在
CountingSink
类中时,你有没有遇到任何错误?我已经在Android上测试了这段代码。从Listener.onProgress()传入的百分比顺序错误:0、1、2、0、1、2,然后我得到了以下异常:java.net.SocketException:sendto失败:由android.system.ErrnoException:sendto失败:ECONNRESET ECONNRESET(由对等方重置连接)请避免使用答案评论其他答案。这应该是对苏拉布答案的评论。@Saurabh write()方法有时会在慢速网络上被调用数次。所以实际的百分比超过了100%。你遇到过这个问题吗?没有,你说的“几次”是什么意思?多少次?3-4或40-60?您能否提供如何在此RequestBody中包装我的多部分RequestBody的示例?我不知道我做的是否正确,但不知怎么的,进度在几毫秒内跳到了100%,但实际文件的上载时间约为10秒。我发现从我的客户端删除
HttpLoggingInterceptor
阻止了这种情况的发生。此代码示例不正确,使用它将导致程序崩溃。潜在的问题是writeTo()可能会被多次调用,但该类不支持这一点。