场景: 当和第三方接口对接,对方只给一个url时,需要下载到本地
场景:请求网络资源并保存到本地,如PDF,图片
import org.apache.tomcat.util.http.fileupload.IOUtils;
import java.net.URL;
import java.net.URLConnection;
public void downLoadURLContent(){
try {
String requestUrl = "";
URL uri = new URL(requestUrl);
URLConnection urlConnection = uri.openConnection();
urlConnection.setConnectTimeout(60 * 1000);
urlConnection.setConnectTimeout(60 * 1000);
try(BufferedInputStream bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream())) {
// String rootPath = "/download/user/"; //linux写法,不带盘符
String rootPath = "D:\\download\\user"; //windows写法写法
String userPath = "";
String filePath = rootPath + userPath;
File parentFile = new File(filePath).getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try (FileOutputStream out =new FileOutputStream(filePath)) {
/**
* 拷贝的字节大小,如有需要可以将判断字节大小
*/
int copy = IOUtils.copy(bufferedInputStream, out);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}