申请权限

<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以后限制了非加密的流量请求

解决方案:

  1. 在res目录下创建xml文件夹,新建 文件network_security_config.xml
  2. 在文件中输入以下内容:
<?xml version="1.0" encoding="utf-8"?><network-security-config>    <base-config cleartextTrafficPermitted="true" /></network-security-config>
  1. 在AndroidManifest中的application里添加你新建的 xml文件
<application        ****        android:networkSecurityConfig="@xml/network_security_config"        **** >

更多相关文章

  1. android webview file标签点击弹出选择文件或拍照菜单
  2. android 从assets和res中读取文件
  3. Android Bluetooth 文件接收路径修改方法
  4. Android文件图片上传的详细讲解(三)---模式回调类
  5. Android 分别使用Post与Get实现网络图片加载
  6. 搭建Android x86_64及arm64-v8a操作步骤
  7. android XML文件序列化
  8. Android Studio(十二):打包多个发布渠道的apk文件
  9. [置顶] Android——4.2.2 文件系统目录分析

随机推荐

  1. win10下mysql 8.0.16 winx64安装配置方法
  2. Windows10 mysql 8.0.12 非安装版配置启
  3. windows下mysql 8.0.16 安装配置方法图文
  4. CentOS7下mysql 8.0.16 安装配置方法图文
  5. mysql 8.0.16 winx64安装配置方法图文教
  6. 一个mysql死锁场景实例分析
  7. Mysql慢查询优化方法及优化原则
  8. 分享几道关于MySQL索引的重点面试题
  9. CentOS7.x卸载与安装MySQL5.7的操作过程
  10. mysql中mysql-bin.000001是什么文件可以