Okhttp文件下载实现

之前用了okhttputils框架实现下载功能根据数据库的id下载,本次使用okhttp下载,通过在tomcat里面部署绝对的文件路径,根据这个路径在加上文件名就可以下载了。
public void download(){
//String url=“https://XXXXX/uploadfile/downloadFile.up?id=206”;
// String basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + “/okhttp”;
String url=“https://XXXXXX/wavURL/c4846d19-ef97-4290-a3bb-70315045bf25_李华.wav”;

final String fileName = url.split("/")[url.split("/").length - 1];
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
        .get()
        .url(url)
        .build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e("moer", "onFailure: ");;
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
      //  String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LungFile";
        String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AAAFile";
        File file=new File(dirName);
        if (!file.exists()) {
            file.mkdir();
        }
        if (response != null) {
            InputStream is = response.body().byteStream();
            FileOutputStream fos = new FileOutputStream(new File(dirName + "/" + fileName));
            int len = 0;
            byte[] buffer = new byte[2048];
            while (-1 != (len = is.read(buffer))) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();
        }
    }
});

猜你喜欢

转载自blog.csdn.net/qq_39784713/article/details/85879920