android通过url下载文件
之前我们说个用过oss解决服务器带宽太小的问题,最后服务器返回的文件的url
现在我要坐的android 通过返回的url下载文件
URL url = "要下载的文件的url"; HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestProperty("Charset", "UTF-8"); con.setRequestMethod("GET"); InputStream is = con.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedInputStream fis = new BufferedInputStream(is); if (is != null) { int i; while ((i = fis.read()) != -1) { fileOutputStream.write(i); } Log.i("下载", "成功"); } else { Log.i("下载", "失败"); }
注意:之前说过好多次,http等网络请求不能写在主线程。
url是http的话要注意给明文权限。