URL
java.net.URL:Uniform Resource Locators,统一资源定位符
组成部分:协议,主机名或IP,端口号,资源路径
常用的构造方法:
| 方法 | 描述 |
|---|---|
| URL(String spec) | 根据字符串表示形式创建URL对象 |
| URL(String protocol , String host , int port , String file) | 根据指定protocol、host、port、file 创建URL对象 |
| URL(String protocol , String host , String file) | 从指定的protocol、host、file创建一个URL |
| URL(URL context , String spec) | 通过在指定的上下文中解析给定的规范来创建 |
| URL(String protocol, String host, int port, String file, URLStreamHandler handler) | 创建 URL从指定对象 protocol , host , port数, file和 handler |
| URL(URL context, String spec, URLStreamHandler handler) | 通过在指定上下文中使用指定的处理程序解析给定规范来创建URL |
常用的方法:
- getProtocol():获取此URL的协议地址
- getHost():获取此URL的主机名
- getPort():获取此URL的端口号
- getFile():获取此URL的文件名
- getPath():获取此URL的路径部分
- getRef():获取此URL的锚定
URL url = new URL("https://cn.bing.com/search?q=%E7%99%BE%E5%BA%A6");// 获取协议:httpsSystem.out.println(url.getProtocol());// 获取主机:cn.bing.comSystem.out.println(url.getHost());// 获取端口:-1System.out.println(url.getPort());// 获取默认端口:443System.out.println(url.getDefaultPort());// 获取路径名:/searchSystem.out.println(url.getPath());// 获取文件:/search?q=%E7%99%BE%E5%BA%A6System.out.println(url.getFile());
从URL中获取连接:
- InputStream openStream():打开此URL,并返回一个InputStream,以便从该连接读取
- URLConnection openConnection():返回一个URLConnection实例,表示与URL引用的远程对象的URL
网页下载:
URL url = new URL("https://cn.bing.com/search?q=%E7%99%BE%E5%BA%A6");try(InputStream inputStream = url.openStream();){byte[] bytes = new byte[1024];// 使用ByteArrayOutputStream进行收集ByteArrayOutputStream aos = new ByteArrayOutputStream();int read = 0;while ((read = inputStream.read(bytes)) != -1) {aos.write(bytes, 0, read);}// 将ByteArrayOutputStream中的数据写入系统标准输出aos.writeTo(System.out);} catch (IOException e) {e.printStackTrace();}
