URL
统一资源定位符:定位资源的,定位互联网上的某一个资源
DNS域名解析 www.baidu.com--->ip
协议://ip地址:端口/项目名/资源 |
URL类:
package com.wzz.A04网络编程;
import java.net.MalformedURLException;
import java.net.URL;
public class B07URL {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://www.py.cn/code/31340.html");
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 com.wzz.A04网络编程;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class B08UrlDown {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("https://m701.music.126.net/20211020174755/6f13a2547ae41b05a80fb9bba778cc2e/jdyyaac/565b/065f/0358/a1cd0e25a815dffcc0c1422398efde9e.m4a");
//2.连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("起风了.mv4");
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);//写出这个数据
}
fos.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}