本文主要介绍文件下载功能的实现,后台来自于:link.
文件上传功能的实现:link.
实现效果:
实现思路: 连接后台接口,获取存储路径,将图片以文件流的形式下载
实现步骤:
- 申请网络权限
- 设置URL
- 获取请求头中要下载文件的文件名
- 获取存储路径
- 利用fileoutputstream写入
- 关流
——————————————————————————————————————————————————————————————————————
1、申请网络权限
一共需要申请两个权限,第一个权限是连接网络的权限(在此之前如果使用的是模拟机记得把模拟机联网:link.),第二个权限是安卓27版本需要使用HTTPS协议(但是该权限不添加我这里也能运行,不过保险起见还是添加上!)
网络连接权限:
<uses-permission android:name="android.permission.INTERNET" />
htts权限: 此处有两种方式可以选择,任选一种即可:
①:android:usesCleartextTraffic="true"
②:android:networkSecurityConfig="@xml/network_security_config"
此时,要对应的创建一个network_security_config.xml文件,文件内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">example.com</domain>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.sunofbeach.net</domain>
<domain includeSubdomains="true">imgs.sunofbeaches.com</domain>
</domain-config>
</domain-config>
</network-security-config>
example.com:项目包名
bkimg.cdn.bcebos.com:域名
如果想要动态获取读写权限可以看这篇博客: link.
2、设置URL
URL url = new URL(BASE_URL + "/download/12");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9");
connection.setRequestProperty("accept", "application/json, text/plain, */*");
connection.connect();