URL下载网络资源-2022-12-20
URL 统一资源定位符,定位互联网的某一个资源
DNS 域名解析 WWW.BAIDU.COM 解析成 XXX.X.X.XXX 本质就是把一个域名解析成一个IP
https: 协议 // IP地址:端口 / 项目名 / 具体资源
www.baidu.com/
Tomcat 要打开
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("http://localhost:8080/lr/security.text");
//2.连接这个资源
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
//3.下载这个资源
FileOutputStream fos = new FileOutputStream("security.text");
byte[] buffer2 = new byte[1024];
int len;
while ((len = inputStream.read(buffer2))!=-1) {
fos.write(buffer2,0,len);
}
//4.关闭资源
fos.close();
inputStream.close();
connection.disconnect();
}
}