- URL:(Uniform Resource Locator) 统一资源定位符 他标识Internet上某一资源的地址
- URL的基本结构由5个部分组成
传输协议://主机名称:端口号/文件名#片段名?参数列表
例:https://yazhouse8.com/article.php?cate=1
片段名: 锚点
/**
* @author:LYY 创建时间:2022/5/11
*/
public class URLTest {
/**
* 下载资源
* 从指定的url下载资源
*/
@Test
void test01() {
FileOutputStream fileOutputStream = null;
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
// url对象 相当于在内存中记录的信息
URL url = new URL("https://i.17173cdn.com/9ih5jd/YWxqaGBf/forum/202204/27/hFMSfNbqbuAcayq.gif");
// 获取链接对象
urlConnection = (HttpURLConnection) url.openConnection();
// 打开链接
urlConnection.connect();
// 获取输入流
inputStream = urlConnection.getInputStream();
// 获取输出流 将文件保存到本地硬盘
fileOutputStream = new FileOutputStream("hFMSfNbqbuAcayq.gif");
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放资源
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
@Test
void test() {
try {
URL url = new URL("https://yazhouse8.com/article.php?cate=1");
// 输出url协议
System.out.println(url.getProtocol());
// 输出url ip
System.out.println(url.getHost());
// 输出url 端口号
System.out.println(url.getPort());
// 输出文件路径
System.out.println(url.getPath());
// 输出url查询条件
System.out.println(url.getQuery());
// 输出资源路径
System.out.println(url.getFile());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}