当前位置: 首页 > news >正文

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

HttpURLConnection使用GET下载zip文件

  • http get下载zip文件
    • MainActivity.java
    • AndroidMainfest.xml
    • activity_main.xml
    • log

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";@Overrideprotected 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() {@Overridepublic void onClick(View view) {Log.i(TAG, "onClick");download_2();}});bt_post2.setOnClickListener(new View.OnClickListener() {@Overridepublic 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();}}}}
}
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> {@Overrideprotected 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;}
}

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" /><applicationandroid: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>

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"><Buttonandroid:id="@+id/bt_post"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="POST" /><Buttonandroid:id="@+id/bt_post2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="POST2" />
</LinearLayout>

log

点击按钮回显如下

I/MainActivity3 lxh: onClick
I/lxh: doInBackground
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/lxh: download okI/MainActivity3 lxh: onClick
I/MainActivity3 lxh: download_3
I/MainActivity3 lxh: responseCode=200
I/MainActivity3 lxh: download ok

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

相关文章:

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

HttpURLConnection使用GET下载zip文件 http get下载zip文件MainActivity.javaAndroidMainfest.xmlactivity_main.xmllog http get下载zip文件 MainActivity.java 用HttpURLConnection GET方法进行需注意&#xff1a; 1、Android 9及以上版本需要设置这个&#xff0c;否则会有…...

phantom3D模体

phantom是人头模型&#xff0c;分为2D和3D两种&#xff0c;matlab中可直接调用phantom(size)生成2D数据&#xff0c;如图1&#xff0c;而三维需要对应函数文件&#xff0c;下载&#xff1a;3D 图1 2D phantom 3D模体为一个椭球体&#xff0c;只能生成xyz三个方向相同维度的模…...

贪心算法解决批量开票限额的问题

具体问题&#xff1a;批量订单开票 限制&#xff1a;1.开最少的张数 2.每张限额10w # 贪心算法 def split_invoice_by_item(items):items_sorted sorted(items, keylambda x: x.price, reverseTrue)invoices []for item in items_sorted:# 尝试将商品加入已有的发票中added …...

Unity后台登录/获取数据——BestHTTP的使用Get/Post

一、使用BestHTTP实现登录功能&#xff08;Post&#xff09; 登录具体的步骤如下&#xff1a; 1&#xff1a;传入你的用户名和密码&#xff0c;这是一条包括链接和用户名密码的链接 2&#xff1a;使用BestHTTP的Post功能将链接传到服务器后台 3&#xff1a;后台拿到了你传送…...

【Windows日志】记录系统事件的日志

文章目录 一、概要二、Windows日志介绍 2.1 应用程序日志2.2 系统日志2.3 安全日志 三、查看与分析日志四、常见事件ID 4.1 登录事件 4.1.1 4624登陆成功4.1.2 4625登陆失败 4.2 特权使用4.3 账户管理事件4.4 账户登录事件5.2 事件ID汇总 一、概要 Windows主要有以下三类日…...

物联网开发学习笔记——目录索引

什么是物联网&#xff1f; 物联网的英文名称是Internet of Things。IoT则是Internet of Things的缩写。 通俗地说&#xff0c;就是把设备与互联网连接起来&#xff0c;进行信息交互。 目录 一、开发环境配置 工欲善其事必先利其器&#xff0c;首先是开发环境配置。 开发环…...

Prometheus:优秀和强大的监控报警工具

文章目录 概述Prometheus的底层技术和原理数据模型数据采集数据存储查询语言数据可视化 Prometheus的部署Prometheus的使用配置数据采集目标查询监控数据设置警报规则 查看数据可视化总结 概述 Prometheus是一款开源的监控和警报工具&#xff0c;用于收集和存储系统和应用程序…...

Appium

# 获取元素和屏幕截图 echo on adb shell uiautomator dump /sdcard/app.uix adb pull /sdcard/app.uix F:\APP\app.uixadb shell screencap -p /sdcard/app.png adb pull /sdcard/app.png F:\APP\app.png卸载appium npm uninstall appium -g 重新安装appium npm install -g a…...

自动驾驶学习笔记(五)——绕行距离调试

#Apollo开发者# 学习课程的传送门如下&#xff0c;当您也准备学习自动驾驶时&#xff0c;可以和我一同前往&#xff1a; 《自动驾驶新人之旅》免费课程—> 传送门 《2023星火培训【感知专项营】》免费课程—>传送门 文章目录 前言 调试内容 打开在线编辑器 打开pl…...

【Android】VirtualDisplay创建流程及原理

Android VirtualDisplay创建流程及原理 Android DisplayManager提供了createVirtualDisplay接口&#xff0c;用于创建虚拟屏。虚拟屏可用于录屏&#xff08;网上很多资料说这个功能&#xff09;&#xff0c;分屏幕&#xff08;比如一块很长的屏幕&#xff0c;通过虚拟屏分出不…...

Linux服务器快速搭建pytorch

Linux服务器搭建pytorch 文章目录 Linux服务器搭建pytorch一、使用FileZilla传输Anaconda二、激活Anaconda环境1.创建一个虚拟环境2.使用已有项目生成requirements.txt3.在虚拟环境中使用requirements.txt安装其他项目相关库 总结 一、使用FileZilla传输Anaconda 提示&#xf…...

声音克隆,定制自己的声音,使用最新版Bert-VITS2的云端训练+推理记录

说明 本次训练服务器使用Google Colab T4 GPUBert-VITS2库为&#xff1a;https://github.com/fishaudio/Bert-VITS2&#xff0c;其更新较为频繁&#xff0c;使用其2023.10.12的commit版本&#xff1a;主要参考&#xff1a;B站诸多大佬视频&#xff0c;CSDN:https://blog.csdn.…...

LeetCode讲解篇之198. 打家劫舍

LeetCode讲解篇之198. 打家劫舍 文章目录 LeetCode讲解篇之198. 打家劫舍题目描述题解思路题解代码 题目描述 题解思路 该问题可以通过递推来完成 递推公式&#xff1a; 前n间房的最大金额 max&#xff08;前n-1间房的最大金额&#xff0c; 前n-2间房的最大金额第n-1间房的最…...

【下载共享文件】Java基于SMB协议 + JCIFS依赖下载Windows共享文件(亲测可用)

这篇文章,主要介绍如何使用JCIFS依赖库,基于SMB协议下载Windows共享文件。 目录 一、搭建Windows共享文件服务 1.1、创建共享文件目录 1.2、添加文件...

【评分卡实现】应用Python中的toad.ScoreCard函数实现评分卡

逻辑回归已经在各大银行和公司都实际运用于业务。之前的文章已经阐述了逻辑回归三部曲——逻辑回归和sigmod函数的由来、...

【数据结构】双链表的相关操作(声明结构体成员、初始化、判空、增、删、查)

双链表 双链表的特点声明双链表的结构体成员双链表的初始化带头结点的双链表初始化不带头结点的双链表初始化调用双链表的初始化 双链表的判空带头结点的双链表判空不带头结点的双链表判空 双链表的插入&#xff08;按值插入&#xff09;头插法建立双链表带头结点的头插法每次调…...

解析找不到msvcp140.dll的5个解决方法,快速修复dll丢失问题

​在使用计算机过程中&#xff0c;我们也会遇到各种各样的问题。其中&#xff0c;找不到msvcp140.dll修复方法是一个非常普遍的问题。msvcp140.dll是一个动态链接库文件&#xff0c;它是Microsoft Visual C 2015 Redistributable的一部分。这个文件包含了许多用于运行C程序的函…...

代码管理工具 gitlab实战应用

系列文章目录 第一章 Java线程池技术应用 第二章 CountDownLatch和Semaphone的应用 第三章 Spring Cloud 简介 第四章 Spring Cloud Netflix 之 Eureka 第五章 Spring Cloud Netflix 之 Ribbon 第六章 Spring Cloud 之 OpenFeign 第七章 Spring Cloud 之 GateWay 第八章 Sprin…...

小谈设计模式(27)—享元模式

小谈设计模式&#xff08;27&#xff09;—享元模式 专栏介绍专栏地址专栏介绍 享元模式模式结构分析享元工厂&#xff08;FlyweightFactory&#xff09;享元接口&#xff08;Flyweight&#xff09;具体享元&#xff08;ConcreteFlyweight&#xff09;非共享具体享元&#xff0…...

网络代理技术:隐私保护与安全加固的利器

随着数字化时代的不断演进&#xff0c;网络安全和个人隐私保护变得愈发重要。在这个背景下&#xff0c;网络代理技术崭露头角&#xff0c;成为网络工程师和普通用户的得力助手。本文将深入探讨Socks5代理、IP代理&#xff0c;以及它们在网络安全、爬虫开发和HTTP协议中的关键应…...

高等数学(下)题型笔记(八)空间解析几何与向量代数

目录 0 前言 1 向量的点乘 1.1 基本公式 1.2 例题 2 向量的叉乘 2.1 基础知识 2.2 例题 3 空间平面方程 3.1 基础知识 3.2 例题 4 空间直线方程 4.1 基础知识 4.2 例题 5 旋转曲面及其方程 5.1 基础知识 5.2 例题 6 空间曲面的法线与切平面 6.1 基础知识 6.2…...

Axios请求超时重发机制

Axios 超时重新请求实现方案 在 Axios 中实现超时重新请求可以通过以下几种方式&#xff1a; 1. 使用拦截器实现自动重试 import axios from axios;// 创建axios实例 const instance axios.create();// 设置超时时间 instance.defaults.timeout 5000;// 最大重试次数 cons…...

代码随想录刷题day30

1、零钱兑换II 给你一个整数数组 coins 表示不同面额的硬币&#xff0c;另给一个整数 amount 表示总金额。 请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额&#xff0c;返回 0 。 假设每一种面额的硬币有无限个。 题目数据保证结果符合 32 位带…...

苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会

在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...

k8s从入门到放弃之HPA控制器

k8s从入门到放弃之HPA控制器 Kubernetes中的Horizontal Pod Autoscaler (HPA)控制器是一种用于自动扩展部署、副本集或复制控制器中Pod数量的机制。它可以根据观察到的CPU利用率&#xff08;或其他自定义指标&#xff09;来调整这些对象的规模&#xff0c;从而帮助应用程序在负…...

jdbc查询mysql数据库时,出现id顺序错误的情况

我在repository中的查询语句如下所示&#xff0c;即传入一个List<intager>的数据&#xff0c;返回这些id的问题列表。但是由于数据库查询时ID列表的顺序与预期不一致&#xff0c;会导致返回的id是从小到大排列的&#xff0c;但我不希望这样。 Query("SELECT NEW com…...

麒麟系统使用-进行.NET开发

文章目录 前言一、搭建dotnet环境1.获取相关资源2.配置dotnet 二、使用dotnet三、其他说明总结 前言 麒麟系统的内核是基于linux的&#xff0c;如果需要进行.NET开发&#xff0c;则需要安装特定的应用。由于NET Framework 是仅适用于 Windows 版本的 .NET&#xff0c;所以要进…...

Appium下载安装配置保姆教程(图文详解)

目录 一、Appium软件介绍 1.特点 2.工作原理 3.应用场景 二、环境准备 安装 Node.js 安装 Appium 安装 JDK 安装 Android SDK 安装Python及依赖包 三、安装教程 1.Node.js安装 1.1.下载Node 1.2.安装程序 1.3.配置npm仓储和缓存 1.4. 配置环境 1.5.测试Node.j…...

Qt 按钮类控件(Push Button 与 Radio Button)(1)

文章目录 Push Button前提概要API接口给按钮添加图标给按钮添加快捷键 Radio ButtonAPI接口性别选择 Push Button&#xff08;鼠标点击不放连续移动快捷键&#xff09; Radio Button Push Button 前提概要 1. 之前文章中所提到的各种跟QWidget有关的各种属性/函数/方法&#…...

【版本控制】Git 和 GitHub 入门教程

目录 0 引言1 Git与GitHub的诞生1.1 Git&#xff1a;Linus的“两周奇迹”&#xff0c;拯救Linux内核1.2 GitHub&#xff1a;为Git插上协作的翅膀1.3 协同进化&#xff1a;从工具到生态的质变1.4 关键历程时间轴&#xff08;2005–2008&#xff09; 2 Git与GitHub入门指南2.1 Gi…...