Java之网络编程学习笔记十 —— URL下载网络资源
程序员文章站
2022-05-06 08:02:33
...
Java之网络编程学习笔记十 —— URL下载网络资源
https://www.baidu.com/
url: 统一资源定位符,定位互联网上的某一个资源
DNS域名解析 www.baidu.com --> ip
url 格式
协议://ip地址:端口号/项目名/资源
常用方法
package pers.ylw.lesson04;
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/helloword/index.jsp?username=ylw&password=123");
//常用方法
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 pers.ylw.lesson04;
import javax.net.ssl.HttpsURLConnection;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class UrlDown {
public static void main(String[] args) throws IOException {
//随便网上找一个下载地址
URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588093919567&di=8d3df5a53cc6043bf0c3a833ca9da6e5&imgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F35%2F34%2F19300001295750130986345801104.jpg");
//连接到这个资源
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
//获得流
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("图片.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len); //写出这个数据
}
fos.close();
inputStream.close();
urlConnection.disconnect();
}
}
上一篇: 算法16 Word Search