https://www.baidu.com
统一资源定位符: 统一资源定位符,又叫做网页地址,是互联网上标准的资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。
DNS域名解析 https://www.baidu.com
=> 183.232.231.172
,域名解析就是域名到IP地址的转换过程,它是把域名指向网站空间IP,让人们通过注册的域名可以方便地访问到网站的一种服务。
协议://ip地址:端口/项目名/资源
示例:
package net.url;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURL {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/HelloWorld/index.jsp?username=tianjiao&password=317525");
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());// 参数
}
}
运行结果:
URL下载网络资源
示例:
package net.url;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws IOException {
// 1.下载地址
URL url = new URL("https://m701.music.126.net/20210220205331/dbfa3bbae67ab9cf7a5079c5afac81de/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/7282034514/6e0d/a7a8/e100/c9c961fb1c06d54f4ef3b6b164ec5098.m4a");
// 2.连接到这个资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("星沉大海.m4a");
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);// 写出这个数据
}
// 关闭资源
fileOutputStream.close();
inputStream.close();
urlConnection.disconnect();
}
}
运行结果:
我们去文件管理: