申请权限

<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 第三方库使用笔记
  2. Android文件图片上传的详细讲解(三)---模式回调类
  3. Android(安卓)Bluetooth 文件接收路径修改方法
  4. 如何更换Android系统默认字体(Android6.0)
  5. android webview file标签点击弹出选择文件或拍照菜单
  6. android 6.0及以上危险权限的获取
  7. android 从assets和res中读取文件
  8. Android(安卓)怎样使用已存在的Database
  9. NPM 和webpack 的基础使用

随机推荐

  1. Android(安卓)中 BroadcastReceiver以及
  2. Camera.Parameters android相机参数
  3. Android TextView设置阴影效果
  4. Android(安卓)UI规范,就这么不受待见吗?
  5. Android 自定义View实现直播点赞特效
  6. Java环境变量和Android环境变量
  7. Binder系列1—Binder Driver初探
  8. Java加密解密工具(适用于JavaSE/JavaEE/An
  9. android图表引擎AchartEngine制作柱图源
  10. android Monkey test测试