Android 文件下载三种基本方式

  private void downloadFile3(){

  //下载路径,如果路径无效了,可换成你的下载路径

  final String url = "http://c.qijingonline.com/test.mkv";

  final long startTime = System.currentTimeMillis();

  Log.i("DOWNLOAD","startTime="+startTime);

  Request request = new Request.Builder().url(url).build();

  new OkHttpClient().newCall(request).enqueue(new Callback() {

  @Override

  public void onFailure(Call call, IOException e) {

  // 下载失败

  e.printStackTrace();

  Log.i("DOWNLOAD","download failed");

  }

  @Override

  public void onResponse(Call call, Response response) throws IOException {

  Sink sink = null;

  BufferedSink bufferedSink = null;

  try {

  String mSDCardPath= Environment.getExternalStorageDirectory().getAbsolutePath();

  File dest = new File(mSDCardPath, url.substring(url.lastIndexOf("/") + 1));

  sink = Okio.sink(dest);

  bufferedSink = Okio.buffer(sink);

  bufferedSink.writeAll(response.body().source());

  bufferedSink.close();

  Log.i("DOWNLOAD","download success");

  Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));

  } catch (Exception e) {

  e.printStackTrace();

  Log.i("DOWNLOAD","download failed");

  } finally {

  if(bufferedSink != null){

  bufferedSink.close();

  }

  }

  }

  });

  }