• Android Studio的笔记--HttpURLConnection使用GET下载zip文件


    http get下载zip文件

    MainActivity.java

    用HttpURLConnection GET方法进行需注意:
    1、Android 9及以上版本需要设置这个,否则会有警告
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }
    2、清单中要申请网络权限写入权限
    < uses-permission android:name=“android.permission.INTERNET” />
    < uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
    3、要在application中添加android:usesCleartextTraffic=“true”。否则会有警告,好像加这个有风险,没有细研究
    4、关于下载的位置Environment.getExternalStorageDirectory()的路径在/storage/emulated/0
    5、关于下载的测试地址http://nginx.org/download/nginx-1.23.4.zip
    6、关于下载的两种方式

    package com.lxh.romupgrade;
    import androidx.appcompat.app.AppCompatActivity;
    import android.content.Context;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    public class MainActivity extends AppCompatActivity {
        Button bt_post;
        Button bt_post2;
        Context mcontext;
        private static final String TAG = "MainActivity3 lxh";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bt_post = findViewById(R.id.bt_post);
            bt_post2 = findViewById(R.id.bt_post2);
            mcontext = MainActivity.this;
            bt_post.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "onClick");
                    download_2();
                }
            });
            bt_post2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "onClick");
                    // Android 9及以上版本需要设置这个,否则会有警告
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    download_3();
                }
            });
        }
        private void download_2() {
            new DownloadZipFileTask().execute();
        }
        public static void download_3() {
            Log.i(TAG, "download_3");
            String url = "http://nginx.org/download/nginx-1.23.4.zip";
            FileOutputStream fos = null;
            InputStream in = null;
            try {
                URL u = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                conn.setRequestMethod("GET");
                int responseCode = conn.getResponseCode();
                Log.i(TAG, "responseCode=" + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/file3.zip");
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = conn.getInputStream().read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    conn.getInputStream().close();
                    Log.i(TAG, "download ok");
                } else {
                    Log.i(TAG, "Handle error case here");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    package com.lxh.romupgrade;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.util.Log;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    /**
     * create by lxh on 2023/10/10 Time:20:21
     * tip:HTTP 下载
     */
    public class DownloadZipFileTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            Log.i("lxh", "doInBackground");
            try {
                URL url = new URL("http://nginx.org/download/nginx-1.23.4.zip");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                int fileSize = connection.getContentLength();
                InputStream inputStream = connection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/file2.zip");
                byte[] buffer = new byte[4096];
                int bytesRead;
                int totalBytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    int progress = (int) (totalBytesRead * 100 / fileSize);
                    publishProgress(progress);
                }
    
                Log.i("lxh", "download ok");
                outputStream.close();
                inputStream.close();
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    AndroidMainfest.xml

    需要在清单添加

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.lxh.romupgrade">
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
            android:theme="@style/Theme.Romupgrade">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    activity_main.xml

    布局如下

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <Button
            android:id="@+id/bt_post"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="POST" />
        <Button
            android:id="@+id/bt_post2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="POST2" />
    </LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    log

    点击按钮回显如下

    I/MainActivity3 lxh: onClick
    I/lxh: doInBackground
    D/NetworkSecurityConfig: No Network Security Config specified, using platform default
    I/lxh: download ok
    
    I/MainActivity3 lxh: onClick
    I/MainActivity3 lxh: download_3
    I/MainActivity3 lxh: responseCode=200
    I/MainActivity3 lxh: download ok
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    待补充
    欢迎指错,一起学习

  • 相关阅读:
    二叉树的遍历方式和代码
    Leetcode29:两数相除
    数字经济的新时代:探索 Web3 的全球影响
    On-Device Neural Net Inference with Mobile GPUs
    【wiki知识库】04.SpringBoot后端实现电子书的增删改查以及前端界面的展示
    进程间通信之共享内存
    php代码比对工具优化版
    MFC使用system有弹黑窗的解决 用WinExec(szBuffer, SW_HIDE);代替
    让代码帮我们写代码(一)
    flutter系列之:Material中的3D组件Card
  • 原文地址:https://blog.csdn.net/weixin_45208598/article/details/133769434