OKHTTP 3跟踪分段上传进度

Sou*_*abh 12 android okhttp3

如何在OkHttp 3中跟踪上传的进度我可以找到v2但不是v3的答案,就像这样

来自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());
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*abh 13

你可以装饰你的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

查看此链接了解更多信息.

  • @Saurabh有时会通过缓慢的网络多次调用write()方法。因此实际百分比超过100%。你遇到这个问题了吗? (2认同)
  • 你能举例说明如何在我的RequestBody中包装我的MultiPart RequestBody吗?我不知道我正确地做了什么,但不知何故,进度在几毫秒内跳到100%,但实际文件需要大约10秒才能上传. (2认同)

pto*_*son 5

我无法得到任何适合我的答案。问题在于,在上传图像之前,进度将运行到 100%,这表明在通过网络发送数据之前,某些缓冲区已被填满。经过一番研究,我发现确实如此,该缓冲区是 Socket 发送缓冲区。向 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在 Retrofit2 中使用它。一般用法是这样的:

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.
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我正在取得进展,但我会看到 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
    }
}
Run Code Online (Sandbox Code Playgroud)

在配置期间,设置它。

val clientBuilder = OkHttpClient.Builder()
    .socketFactory(ProgressFriendlySocketFactory())
Run Code Online (Sandbox Code Playgroud)

正如其他人所提到的,记录请求正文可能会影响这一点并导致数据被多次读取。要么不要记录正文,要么我所做的就是为 CountingRequestBody 关闭它。为此,我编写了自己的 HttpLoggingInterceptor,它解决了这个问题和其他问题(例如记录 MultipartBody)。但这超出了这个问题的范围。

if(requestBody is CountingRequestBody) {
  // don't log the body in production
}
Run Code Online (Sandbox Code Playgroud)

另一个问题是 MockWebServer。我有一个使用 MockWebServer 和 json 文件的风格,所以我的应用程序可以在没有网络的情况下运行,这样我就可以在没有负担的情况下进行测试。要使此代码工作,Dispatcher 需要读取正文数据。我创建了这个 Dispatcher 来做到这一点。然后它将调度转发到另一个 Dispatcher,例如默认的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在 MockWebServer 中使用它作为:

var server = MockWebServer()
server.setDispatcher(BodyReadingDispatcher(QueueDispatcher()))
Run Code Online (Sandbox Code Playgroud)

这是我项目中的所有工作代码。我确实出于插图目的而将其拉出。如果开箱即用它对您不起作用,我深表歉意。