在 android 中使用 MultipartBuilder 取得进展

Get progress by using MultipartBuilder in android

我正在使用 okhttp 将 http 表单发送到服务器。这是我的要求:

OkHttpClient client = new OkHttpClient();     
RequestBody multiPartBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addPart(
                                Headers.of("Content-Disposition", "form-data; name=\"file0\"; filename=\"" + name.split("\.")[0] + "\""),
                                RequestBody.create(MediaType.parse(mediaType), new File(path)))
                        .addFormDataPart("RadUAG_fileName", name)
                        .addFormDataPart("RadUAG_position", "0")
    Request request = new Request.Builder()
                        .url("http://xxx.xxx.xxx.xxx/ArchiveSite/Handlers/RadUploadHandler.ashx")
                        .post(multiPartBody)
                        .build();
    client.newCall(request).execute()

现在假设我的文件很大,我想向用户显示上传到服务器的进度。

如何获取发送到服务器的文件装载量并显示给用户进度条?

如您所见,我正在使用 okhttp,我想在此库中找到解决方案。

我发现这个 example 可以自定义 RequestBody

所以我创建 CountingFileRequestBody class:

public class CountingFileRequestBody extends RequestBody {

    private static final int SEGMENT_SIZE = 2048;
    private final File file;
    private final ProgressListener listener;
    private final String contentType;

    public CountingFileRequestBody(File file, String contentType, ProgressListener listener) {
        this.file = file;
        this.contentType = contentType;
        this.listener = listener;
    }

    @Override
    public long contentLength() {
        return file.length();
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(contentType);
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(file);
            long total = 0;
            long read;

            while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                total += read;
                sink.flush();
                this.listener.transferred(total);

            }
        } finally {
            Util.closeQuietly(source);
        }
    }

    public interface ProgressListener {
        void transferred(long num);
    }
}

在主要部分 activity 我这样使用:

RequestBody multiPartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"file0\"; filename=\"" + name.split("\.")[0] + "\""),
                        new CountingFileRequestBody(new File(path), mediaType, new CountingFileRequestBody.ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                float progress = (num / (float) totalSize) * 100;
                                handler.post(() -> {
                                    mProgress.setProgress((int) progress);
                                    tvProgressPercentage.setText((int) progress + "%");
                                });
                            }
                        }))
                .addFormDataPart("RadUAG_fileName", name)

现在我要向用户展示一个进度:-)