okhttp下载文件,下载apk

okhttp下载文件,重要的就是依赖okhttp,内存读取权限

//权限
implementation'com.yanzhenjie:permission:2.0.3'
//网络
implementation'com.squareup.okhttp3:okhttp:3.10.0'  

权限

<!--网络权限问题-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--8.0安装需要的权限-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!--读写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

权限申请

AndPermission.with(this)
.runtime()
.permission(Permission.Group.STORAGE)
.onGranted(permissions -> {
// Storage permission are allowed.
        })
.onDenied(permissions -> {
// Storage permission are not allowed.
        })
.start();

下载代码

public class OkHttpDownUtils {

    private static OkHttpDownUtils instance = new OkHttpDownUtils();//单例
    private final String TAG="update";
    private File file;
    public static OkHttpDownUtils getInstance() {
        return instance;
    }
    public void downFile(final String url){
            get(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure" + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;//输入流
                    FileOutputStream fos = null;//输出流
                    try {
                        is = response.body().byteStream();//获取输入流
                        long total = response.body().contentLength();//获取文件大小
                        if (is != null) {
                            Log.d("SettingPresenter", "onResponse: 不为空");
                            // 设置路径
                            file = new File(Environment.getExternalStorageDirectory(), "youehu.apk");
                            fos = new FileOutputStream(file);
                            byte[] buf = new byte[1024];
                            int ch = -1;
                            int process = 0;
                            while ((ch = is.read(buf)) != -1) {
                                fos.write(buf, 0, ch);
                                process += ch;
                            }

                        }
                        fos.flush();
                        // 下载完成
                        if (fos != null) {
                            fos.close();
                        }
                        //down();
                        Log.e(TAG, "onFailure" + file.getPath());
                        //view.showSuccess();
                    } catch (Exception e) {
                        Log.e(TAG, e.toString());
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                }
            });
    }
    /**
     * post请求
     * @param address
     * @param callback
     * @param map
     */

    public void post(String address, okhttp3.Callback callback, Map<String, String> map)
    {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        if (map!=null)
        {
            for (Map.Entry<String, String> entry:map.entrySet())
            {
                builder.add(entry.getKey(),entry.getValue());
            }
        }
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(address)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * get请求
     * @param address
     * @param callback
     */

    public void get(String address, okhttp3.Callback callback)
    {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。