android - OKHTTP 3 跟踪分段上传进度

标签 android okhttp

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

来自 OkHttp 配方的示例多部分请求

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 实例将你的 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了解更多。

关于android - OKHTTP 3 跟踪分段上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528751/

相关文章:

java - 通过 OkHttp 拦截器拦截和重试调用

android - 使用 OkhttpClient 3.2 和 Retrofit 2 发送视频时出现 java.net.SocketTimeoutException

android - 如何使用 MOSHI 将 un json 字符串解析为列表

android - TextView.setText()使我的应用程序崩溃

java - 如何获取原始文件夹android中的字符串文件名(我的音频文件)

android - 如何滚动到 Horizo​​ntalScrollView subview 的中心?

android - 为什么 OkHttp 会默默地替换掉 ws ://or wss://schemes?

android - 在 Android 中将 setZOrderOnTop 设置为 true 的 SurfaceView 顶部的按钮

android - 使用哪个移动框架?

android - 使用 Retrofit 2 向请求添加 header