【问题标题】:Android Retrofit 2 JSON object upload progress percentageAndroid Retrofit 2 JSON对象上传进度百分比
【发布时间】:2017-06-07 18:40:20
【问题描述】:

我正在使用 Retrofit 2 将 JSON 上传到服务器。 JSON 有一些 BASE64 编码的图像,因此上传整个图像需要时间。我想查看上传的百分比。我已经找到了现有文件的解决方案,但这不是文件,服务器只接受这种形式。

【问题讨论】:

    标签: android json upload retrofit progress


    【解决方案1】:

    对于有同样问题的其他人,我已经从这个库中改编了一个辅助类(ProgressOutputStream):https://github.com/lizhangqu/CoreProgress,我的工作代码如下:(用于上传文件和上传 json)

    import java.io.IOException;
    
    import okhttp3.MediaType;
    import okhttp3.RequestBody;
    import okio.BufferedSink;
    import okio.Okio;
    
    public class UploadProgressRequestBody extends RequestBody {
        private final RequestBody requestBody;
        private final ProgressListener progressListener;
    
        public UploadProgressRequestBody(RequestBody requestBody) {
            this.requestBody = requestBody;
            this.progressListener = getDefaultProgressListener();
        }
    
        @Override public MediaType contentType() {
            return requestBody.contentType();
        }
    
        @Override public long contentLength() {
            try {
                return requestBody.contentLength();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return -1;
        }
    
        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            if (progressListener == null) {
                requestBody.writeTo(sink);
                return;
            }
            ProgressOutputStream progressOutputStream = new ProgressOutputStream(sink.outputStream(), progressListener, contentLength());
            BufferedSink progressSink = Okio.buffer(Okio.sink(progressOutputStream));
            requestBody.writeTo(progressSink);
            progressSink.flush();
        }
    
        interface ProgressListener {
            void update(long bytesWritten, long contentLength);
        }
    
        private ProgressListener getDefaultProgressListener(){
            ProgressListener progressListener = new UploadProgressRequestBody.ProgressListener() {
                @Override public void update(long bytesRead, long contentLength) {
                    System.out.println("bytesRead: "+bytesRead);
                    System.out.println("contentLength: "+contentLength);
                    System.out.format("%d%% done\n", (100 * bytesRead) / contentLength);
                }
            };
    
            return progressListener;
        }
    
    }
    

    ============

    import java.io.IOException;
    import java.io.OutputStream;
    
    class ProgressOutputStream extends OutputStream {
        private final OutputStream stream;
        private final UploadProgressRequestBody.ProgressListener listener;
    
        private long total;
        private long totalWritten;
    
        ProgressOutputStream(OutputStream stream, UploadProgressRequestBody.ProgressListener listener, long total) {
            this.stream = stream;
            this.listener = listener;
            this.total = total;
        }
    
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            this.stream.write(b, off, len);
            if (this.total < 0) {
                this.listener.update(-1, -1);
                return;
            }
            if (len < b.length) {
                this.totalWritten += len;
            } else {
                this.totalWritten += b.length;
            }
            this.listener.update(this.totalWritten, this.total);
        }
    
        @Override
        public void write(int b) throws IOException {
            this.stream.write(b);
            if (this.total < 0) {
                this.listener.update(-1, -1);
                return;
            }
            this.totalWritten++;
            this.listener.update(this.totalWritten, this.total);
        }
    
        @Override
        public void close() throws IOException {
            if (this.stream != null) {
                this.stream.close();
            }
        }
    
        @Override
        public void flush() throws IOException {
            if (this.stream != null) {
                this.stream.flush();
            }
        }
    }
    

    ===========

        OkHttpClient client = new OkHttpClient.Builder()
        .addNetworkInterceptor(new Interceptor() {
            @Override public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
    
                if (originalRequest.body() == null) {
                    return chain.proceed(originalRequest);
                }
    
                Request progressRequest = originalRequest.newBuilder()
                        .method(originalRequest.method(),
                                new UploadProgressRequestBody(originalRequest.body()))
                        .build();
    
                return chain.proceed(progressRequest);
            }
        }).build();
    
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 2018-12-11
      • 2014-03-05
      相关资源
      最近更新 更多