是我要下载别人的文件,不是我要提供下载接口。
现在我要访问外部的服务器从他那里下载文件然后保存,但是这个该怎么访问呢?
参考:
其实就是通过流的方式来读取就可以,下面代码可以参考
public static boolean download(String urlPath , String targetDirectory,String fileName) throws Exception {
// 解决url中可能有中文情况
URL url = new URL(urlPath);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(3000);
// 设置 User-Agent 避免被拦截
http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
String contentType = http.getContentType();
// 获取文件大小
long length = http.getContentLengthLong();
// 获取文件名
InputStream inputStream = http.getInputStream();
byte[] buff = new byte[1024*10];
File file = new File(targetDirectory, fileName);
if(!file.exists()){
OutputStream out = new FileOutputStream(file);
int len ;
int count = 0; // 计数
while((len = inputStream.read(buff)) != -1) {
out.write(buff, 0, len);
out.flush();
++count ;
}
// 关闭资源
out.close();
inputStream.close();
http.disconnect();
return true;
}
return false;
}