网络编程之URL
URL
-
URL 是 统一资源定位符,用来定位互联网上的某一个资源,比如 www.baidu.com
-
DNS 是域名解析,把域名解析成IP地址
格式:
协议://IP地址:端口/项目名/资源
URL 类中的方法:
package com.network.url;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=zhangsan");
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 com.network.url;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo02 {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("https://m801.music.126.net/20220730170101/972d74fc0cfac98baa9584ab1d7cdb7d/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/14096427565/7854/7b14/6110/6a83aac06435d939143701eebe126ed9.m4a");
//2.连接到这个资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.下载
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("f://test//gu.m4a");
byte[] buffer = new byte[1024];
int count;
while ((count = is.read(buffer)) != -1){
fos.write(buffer);
}
//关闭
fos.close();
is.close();
urlConnection.disconnect();
}
}
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/277891.html