{"id":373,"date":"2023-02-25T08:31:26","date_gmt":"2023-02-25T00:31:26","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=373"},"modified":"2023-04-30T14:40:09","modified_gmt":"2023-04-30T06:40:09","slug":"okhttp3-learning-9-file-upload-interceptor-to-obtain-upload-progress","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/02\/25\/okhttp3-learning-9-file-upload-interceptor-to-obtain-upload-progress\/","title":{"rendered":"OKHttp3\u5b66\u4e60\u4e4b\u4e5d\uff1a\u6587\u4ef6\u4e0a\u4f20\uff08\u62e6\u622a\u5668\u83b7\u53d6\u4e0a\u4f20\u8fdb\u5ea6\uff09"},"content":{"rendered":"<p>\u901a\u8fc7\u91cd\u5199\u8bf7\u6c42\u8fdb\u884c\u6587\u4ef6\u4e0a\u4f20\u62e6\u622a\uff0c\u5b9e\u73b0\u8fdb\u5ea6\u8ba1\u7b97\u3002<\/p>\n<h3>\u5305\u88c5\u8bf7\u6c42\u4f53\uff0c\u5904\u7406\u8fdb\u5ea6<\/h3>\n<p><!-- more --><\/p>\n<pre><code class=\"language-java\">public class ProgressRequestBody extends RequestBody {\n\n    \/\/\u5b9e\u9645\u7684\u5f85\u5305\u88c5\u8bf7\u6c42\u4f53\n    private final RequestBody requestBody;\n    \/\/\u8fdb\u5ea6\u56de\u8c03\u63a5\u53e3\n    private final ProgressListener progressListener;\n    \/\/\u5305\u88c5\u5b8c\u6210\u7684BufferedSink\n    private BufferedSink bufferedSink;\n\n    public ProgressRequestBody(RequestBody requestBody, ProgressListener progressListener) {\n        this.requestBody = requestBody;\n        this.progressListener = progressListener;\n    }\n\n    @Override\n    public MediaType contentType() {\n        return requestBody.contentType();\n    }\n\n    @Override\n    public long contentLength() throws IOException {\n        return requestBody.contentLength();\n    }\n\n    @Override\n    public void writeTo(BufferedSink sink) throws IOException {\n        if (bufferedSink == null) {\n            bufferedSink = Okio.buffer(getSink(sink));\n        }\n        \/\/\u5199\u5165\n        requestBody.writeTo(bufferedSink);\n        \/\/\u5fc5\u987b\u8c03\u7528flush\uff0c\u5426\u5219\u6700\u540e\u4e00\u90e8\u5206\u6570\u636e\u53ef\u80fd\u4e0d\u4f1a\u88ab\u5199\u5165\n        bufferedSink.flush();\n    }\n\n    private Sink getSink(Sink sink) throws IOException {\n        return new ForwardingSink(sink) {\n            long contentLength = contentLength();\n            long writeLength = 0;\n\n            @Override\n            public void write(Buffer source, long byteCount) throws IOException {\n                super.write(source, byteCount);\n                \/\/Log.i(&quot;yezhou&quot;, &quot;ProgressRequestBody: writeLength=&quot; + writeLength + &quot;, byteCount=&quot; + byteCount);\n                if (writeLength &lt; contentLength) {\n                    writeLength += byteCount;\n                    int progress = (int) (writeLength * 1.0f \/ contentLength * 100);\n                    progressListener.onProgress(progress);\n                } else {\n                    progressListener.onDone(contentLength);\n                }\n            }\n        };\n    }\n}<\/code><\/pre>\n<h3>\u5c01\u88c5\u4e0a\u4f20\u8fdb\u5ea6\u62e6\u622a\u5668<\/h3>\n<pre><code class=\"language-java\">public void uploadFileWithInterceptors(View view) {\n    OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {\n        @Override\n        public Response intercept(Chain chain) throws IOException {\n            Request originRequest = chain.request();\n            Request targetRequest = originRequest.newBuilder()\n                    .post(new ProgressRequestBody(originRequest.body(), new MyProgressListener()))  \/\/\u5c01\u88c5\u4e0a\u4f20\u8fdb\u5ea6\u62e6\u622a\u5668\n                    .build();\n            return chain.proceed(targetRequest);\n        }\n    }).build();\n\n    String uploadUrl = SERVER_ADDRESS + &quot;\/upload&quot;;\n    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + &quot;generated.apk&quot;;\n    File file = new File(filePath);\n\n    RequestBody fileBody = RequestBody.create(MediaType.parse(&quot;application\/octet-stream&quot;), file);\n\n    RequestBody requestBody = new MultipartBody.Builder()\n            .setType(MultipartBody.FORM)\n            .addFormDataPart(&quot;username&quot;, &quot;AndroidiOS.cc&quot;)  \/\/Form\u8868\u5355\u53c2\u6570\n            .addFormDataPart(&quot;file&quot;, &quot;AndroidiOS.apk&quot;, fileBody)  \/\/\u6587\u4ef6\u53c2\u6570\n            .build();\n\n    Request request = new Request.Builder().url(uploadUrl).post(requestBody).build();\n    client.newCall(request).enqueue(new Callback() {\n        @Override\n        public void onFailure(Call call, IOException e) {\n            Log.i(TAG, &quot;\u8bf7\u6c42\u5931\u8d25: &quot; + e.getLocalizedMessage());\n        }\n\n        @Override\n        public void onResponse(Call call, Response response) throws IOException {\n            if (response.isSuccessful()) {\n                Log.i(TAG, &quot;\u8bf7\u6c42\u6210\u529f&quot;);\n            }\n        }\n    });\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u901a\u8fc7\u91cd\u5199\u8bf7\u6c42\u8fdb\u884c\u6587\u4ef6\u4e0a\u4f20\u62e6\u622a\uff0c\u5b9e\u73b0\u8fdb\u5ea6\u8ba1\u7b97\u3002 \u5305\u88c5\u8bf7\u6c42\u4f53\uff0c\u5904\u7406\u8fdb\u5ea6 public class Progress [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[116],"tags":[],"class_list":["post-373","post","type-post","status-publish","format-standard","hentry","category-okhttp"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/373","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=373"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/373\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=373"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}