统一资源定位符:定位资源的,定位互联网上的某一个资源
DNS 域名解析
协议://ip地址:端口/项目名/资源
package top.ltyzqhh.Net;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) throws Exception {
URL url = new URL("<http://localhost:8080/helloword/index.jsp?username=ltyzqhh&password=123>");
System.out.println(url.getProtocol());//协议
System.out.println(url.getHost());//主机ip
System.out.println(url.getPort());//端口
System.out.println(url.getPath());//文件
System.out.println(url.getFile());//全路径
System.out.println(url.getQuery());//参数
}
}
网上下载
package top.ltyzqhh.Net;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.下载地址
//URL url = new URL("<https://www.ghibli.jp/gallery/howl049.jpg>");
URL url = new URL("<https://m10.music.126.net/20210502230534/6f89e8ba5eb4ded1604d23e23ae54098/yyaac/obj/wonDkMOGw6XDiTHCmMOi/3228431698/05d9/8b56/c9c2/83b7f1f128e7f9597c7b3da8f4135913.m4a>");
//2.连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("shall We Talk.m4a");
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1)
{
fos.write(buffer,0,len);//写出这个数据
}
fos.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}