URL实现网络下载

URL编程

url类

URL (Uniform Resource Locator): 统一资源定位符,它表示 internet 上某一资源的地址。 它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate:定位这个资源。
通过URL 我们可以访问Internet上的各种网络资源,比如最常见的 www,ftp站点。浏览器通过解析 给定的URL可以在网络上查找相应的文件或其他资源。
URL 的 基本结构由 5部分组成:

传输协议://主机名:端口号/文件名 #片段名?参数列表

例如:http://localhost:8080/helloworld/index.jsp#a?username=MrSun&password=123
片段名,即锚链接,比如我们去一些小说网站,可以直接定位到某个章节位置
参数列表格式 : 参数名=参数值 & 参数名=参数值...

实例化

上代码

import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123");
System.out.println(url.getProtocol()); //获取URL的协议名
System.out.println(url.getHost()); //获取URL的主机名
System.out.println(url.getPort()); //获取URL的端口号
System.out.println(url.getPath()); //获取URL的文件路径
System.out.println(url.getFile()); //获取URL的文件名
System.out.println(url.getQuery()); //获取URL的查询名
} catch (MalformedURLException e) {
e.printStackTrace();
} }
}
下载网易云的歌曲 进行抓包

上代码

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//实现下载
public class URLDemo01 {
public static void main(String[] args) throws Exception {
//1.下载的地址
URL url = new URL("https://m10.music.126.net/20220224150009/735f3efbb6783a6a81d7e3237dd4f099/yyaac/0708/0652/0508/0b9b6827b718aa223af92bd52aa2424f.m4a");
//2.链接到这个资源 用HTTP连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.获得流
InputStream inputStream = urlConnection.getInputStream();
//4.得到的是一个文件 应该进行转换
FileOutputStream fos = new FileOutputStream("世间美好.m4a");
//5.开始读取
byte[] buffer = new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);//6.写出这个数据
}
//7.关闭
fos.close();
inputStream.close();
urlConnection.disconnect();//链接断开是这个方法
}
}

posted @ 2022-03-03 19:41  秃头星人  阅读(116)  评论(0编辑  收藏  举报