当前位置: 首页 > 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协议中的关键应…...

Java-41 深入浅出 Spring - 声明式事务的支持 事务配置 XML模式 XML+注解模式

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; &#x1f680; AI篇持续更新中&#xff01;&#xff08;长期更新&#xff09; 目前2025年06月05日更新到&#xff1a; AI炼丹日志-28 - Aud…...

ElasticSearch搜索引擎之倒排索引及其底层算法

文章目录 一、搜索引擎1、什么是搜索引擎?2、搜索引擎的分类3、常用的搜索引擎4、搜索引擎的特点二、倒排索引1、简介2、为什么倒排索引不用B+树1.创建时间长,文件大。2.其次,树深,IO次数可怕。3.索引可能会失效。4.精准度差。三. 倒排索引四、算法1、Term Index的算法2、 …...

NFT模式:数字资产确权与链游经济系统构建

NFT模式&#xff1a;数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新&#xff1a;构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议&#xff1a;基于LayerZero协议实现以太坊、Solana等公链资产互通&#xff0c;通过零知…...

pikachu靶场通关笔记22-1 SQL注入05-1-insert注入(报错法)

目录 一、SQL注入 二、insert注入 三、报错型注入 四、updatexml函数 五、源码审计 六、insert渗透实战 1、渗透准备 2、获取数据库名database 3、获取表名table 4、获取列名column 5、获取字段 本系列为通过《pikachu靶场通关笔记》的SQL注入关卡(共10关&#xff0…...

html-<abbr> 缩写或首字母缩略词

定义与作用 <abbr> 标签用于表示缩写或首字母缩略词&#xff0c;它可以帮助用户更好地理解缩写的含义&#xff0c;尤其是对于那些不熟悉该缩写的用户。 title 属性的内容提供了缩写的详细说明。当用户将鼠标悬停在缩写上时&#xff0c;会显示一个提示框。 示例&#x…...

《C++ 模板》

目录 函数模板 类模板 非类型模板参数 模板特化 函数模板特化 类模板的特化 模板&#xff0c;就像一个模具&#xff0c;里面可以将不同类型的材料做成一个形状&#xff0c;其分为函数模板和类模板。 函数模板 函数模板可以简化函数重载的代码。格式&#xff1a;templa…...

动态 Web 开发技术入门篇

一、HTTP 协议核心 1.1 HTTP 基础 协议全称 &#xff1a;HyperText Transfer Protocol&#xff08;超文本传输协议&#xff09; 默认端口 &#xff1a;HTTP 使用 80 端口&#xff0c;HTTPS 使用 443 端口。 请求方法 &#xff1a; GET &#xff1a;用于获取资源&#xff0c;…...

iview框架主题色的应用

1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题&#xff0c;无需引入&#xff0c;直接可…...

数学建模-滑翔伞伞翼面积的设计,运动状态计算和优化 !

我们考虑滑翔伞的伞翼面积设计问题以及运动状态描述。滑翔伞的性能主要取决于伞翼面积、气动特性以及飞行员的重量。我们的目标是建立数学模型来描述滑翔伞的运动状态,并优化伞翼面积的设计。 一、问题分析 滑翔伞在飞行过程中受到重力、升力和阻力的作用。升力和阻力与伞翼面…...

Docker、Wsl 打包迁移环境

电脑需要开启wsl2 可以使用wsl -v 查看当前的版本 wsl -v WSL 版本&#xff1a; 2.2.4.0 内核版本&#xff1a; 5.15.153.1-2 WSLg 版本&#xff1a; 1.0.61 MSRDC 版本&#xff1a; 1.2.5326 Direct3D 版本&#xff1a; 1.611.1-81528511 DXCore 版本&#xff1a; 10.0.2609…...