申请权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
API大于6.0时 主动申请权限
public static void ApplyPermission(Context context) {
ActivityCompat.requestPermissions((Activity) context, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET
}, 1);
}
添加okhttp依赖
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
下载文件工具类
public class DownloadUtil {
private static DownloadUtil downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadUtil get() {
if (downloadUtil == null) {
downloadUtil = new DownloadUtil();
}
return downloadUtil;
}
public DownloadUtil() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称
* @param listener 下载监听
*/
public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
Request request = new Request.Builder()
.url(url)
.build();
OkHttpClient client = new OkHttpClient();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
//异步请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败监听回调
listener.onDownloadFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
//储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
//下载中更新进度条
listener.onDownloading(progress);
}
fos.flush();
//下载完成
listener.onDownloadSuccess(file);
} catch (Exception e) {
listener.onDownloadFailed(e);
}finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
});
}
public interface OnDownloadListener{
//下载成功之后的文件
void onDownloadSuccess(File file);
//下载进度
void onDownloading(int progress);
//下载异常信息
void onDownloadFailed(Exception e);
}
}
使用
DownloadUtil.get().download("http://47.112.96.171:8081/in/test.html", "/mnt/sdcard/", "test.html",
new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
Log.e("---------", "onDownloadSuccess");
}
@Override
public void onDownloading(int progress) {
Log.e("---------", "onDownloading");
}
@Override
public void onDownloadFailed(Exception e) {
Log.e("---------", "onDownloadFailed" + e.getMessage());
}
});
NetworkOnMainThreadException异常
解决:网络耗时请求要放在子线程中
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("mylog", "请求结果为-->" + val);
// TODO
// UI界面的更新等相关操作
}
};
/**
* 网络操作相关的子线程
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
// TODO
// 在这里进行 http request.网络请求相关操作
DownloadUtil.get().download("http://47.112.96.171:8081/in/test.html", "/mnt/sdcard/", "test.html",
new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
Log.e("---------", "onDownloadSuccess");
}
@Override
public void onDownloading(int progress) {
Log.e("---------", "onDownloading");
}
@Override
public void onDownloadFailed(Exception e) {
Log.e("---------", "onDownloadFailed" + e.getMessage());
}
});
}
};
//调用
new Thread(networkTask).start();
communication to … not permitted by network security policy异常
网络安全策略不允许与 www…com之间进行明文通信
原因:Android P以后限制了非加密的流量请求
解决方案:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
<application
****
android:networkSecurityConfig="@xml/network_security_config"
****
>