{"id":370,"date":"2023-02-25T08:29:05","date_gmt":"2023-02-25T00:29:05","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=370"},"modified":"2023-04-30T14:40:44","modified_gmt":"2023-04-30T06:40:44","slug":"okhttp3-learning-6-file-download-simple-method","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/02\/25\/okhttp3-learning-6-file-download-simple-method\/","title":{"rendered":"OKHttp3\u5b66\u4e60\u4e4b\u516d\uff1a\u6587\u4ef6\u4e0b\u8f7d\uff08\u7b80\u5355\u65b9\u5f0f\uff09"},"content":{"rendered":"<p>\u9700\u6c42\uff1a\u4e0b\u8f7d\u7f51\u7edc\u6587\u4ef6\u5230\u624b\u673aSD\u5361\u4e0a<\/p>\n<p>\u5728app\u6a21\u5757\u7684build.gradle\u914d\u7f6e<\/p>\n<p><!-- more --><\/p>\n<pre><code>compile &#039;com.squareup.okhttp3:okhttp:3.4.2&#039;<\/code><\/pre>\n<p>\u5b9e\u73b0\u6e90\u7801<\/p>\n<pre><code class=\"language-java\">private static final String fileUrl = &quot;http:\/\/dldir1.qq.com\/weixin\/android\/weixin6331android940.apk&quot;;\nprivate static final String fileName = &quot;weixin6331android940.apk&quot;;\n\npublic void downloadFile(View view) {\n    OkHttpClient client = new OkHttpClient();\n    Request request = new Request.Builder().url(fileUrl).build();\n\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                ResponseBody body = response.body();\n                if (body != null) {\n                    writeFile(body);\n                }\n            }\n        }\n    });\n}\n\n\/\/\u4e3b\u7ebf\u7a0b\u66f4\u65b0UI\u8fdb\u5ea6\nprivate Handler handler = new Handler() {\n    @Override\n    public void handleMessage(Message msg) {\n        switch (msg.what) {\n            case 1:\n                int progress = msg.arg1;\n                mProgressBar.setProgress(progress);\n                break;\n\n            default:\n                break;\n        }\n    }\n};\n\nprivate void writeFile(ResponseBody body) {\n    InputStream is = null;  \/\/\u7f51\u7edc\u8f93\u5165\u6d41\n    FileOutputStream fos = null;  \/\/\u6587\u4ef6\u8f93\u51fa\u6d41\n\n    is = body.byteStream();\n\n    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;\n    File file = new File(filePath);\n    try {\n        fos = new FileOutputStream(file);\n        byte[] buffer = new byte[1024];\n        int len = 0;\n        long totalSize = body.contentLength();  \/\/\u6587\u4ef6\u603b\u5927\u5c0f\n        long sum = 0;\n        while ((len = is.read(buffer)) != -1) {\n            fos.write(buffer, 0, len);\n            sum += len;\n            int progress = (int) (sum * 1.0f \/ totalSize * 100);\n            Message msg = handler.obtainMessage();\n            msg.what = 1;\n            msg.arg1 = progress;\n            handler.sendMessage(msg);\n        }\n\n    } catch (FileNotFoundException e) {\n        e.printStackTrace();\n    } catch (IOException e) {\n        e.printStackTrace();\n    } finally {\n        if (is != null) {\n            try {\n                is.close();\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n        if (fos != null) {\n            try {\n                fos.close();\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u9700\u6c42\uff1a\u4e0b\u8f7d\u7f51\u7edc\u6587\u4ef6\u5230\u624b\u673aSD\u5361\u4e0a \u5728app\u6a21\u5757\u7684build.gradle\u914d\u7f6e compile &#039;co [&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-370","post","type-post","status-publish","format-standard","hentry","category-okhttp"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/370","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=370"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/370\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=370"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=370"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=370"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}