Okhttp进行文件的下载

服务器端有所需要下载的文件,图片或者文本,直接进行请求,可以从response获得服务器返回的流

1.

case R.id.button_activity7_2:
verifyStoragePermissions(MainActivity7.this);
downloadFile("http://192.168.1.8:8080/com.lianggao.whut/images/5.jpg");
break;
//
private void downloadFile(final String url){ new Thread(){ public void run(){ download(url); } }.start(); } //下载 public void download( final String url){ final long startTime = System.currentTimeMillis(); Log.i("DOWNLOAD","startTime="+startTime); Request request = new Request.Builder().url(url).build(); client.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();//SD卡路径 String appPath= getApplicationContext().getFilesDir().getAbsolutePath();//此APP的files路径 Log.i("DOWNLOAD",appPath); File dest = new File(appPath,url.substring(url.lastIndexOf("/") + 1)); sink = Okio.sink(dest); bufferedSink = Okio.buffer(sink); /*InputStream is=response.body().byteStream(); if (is != null) { FileOutputStream fileOutputStream = new FileOutputStream(dest);//指定文件保存路径,代码看下一步 byte[] buf = new byte[1024]; int ch; while ((ch = is.read(buf)) != -1) { System.out.println("@@@@@@@@@@@@@"+ch); fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中 } }*/ //Log.i("DOWNLOADddddd",is.toString()); bufferedSink.writeAll(response.body().source()); Log.i("DOWNLOAD",response.body().source().toString()); 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(); } } } }); }

2.服务器资源要放在webapp下面

 

3.

 

https://blog.csdn.net/suyimin2010/article/details/81270470

 

posted @ 2020-02-16 18:41  七月的四字  阅读(6122)  评论(0编辑  收藏  举报