URI(uniform resource identifier): 统一资源标识符,用来唯一的标识一个资源
URL(uniform resource locator): 统一资源定位器,它是一种具体的URI
四部分组成: 协议 存放资源的主机域名 端口号 资源文件名
package com.kennosaur.net.url;
import java.net.MalformedURLException;
/**
* 1.构建
* URL(String spec) 根据 String 表示形式创建 URL 对象
* URL(URL context, String spec) 通过在指定的上下文中对给定的 spec 进行解析创建 URL
* 2.方法
*
*/
import java.net.URL;
public class Url01 {
public static void main(String[] args) throws MalformedURLException {
//绝对路径构建 #aaa锚点(也称为“引用”)
URL url = new URL("http://www.baidu.com:80/index.html#aaa?username=aaa&pwd=123");
System.out.println("协议:"+url.getProtocol());
System.out.println("域名:"+url.getHost());
System.out.println("端口:"+url.getPort());
System.out.println("资源:"+url.getFile());
System.out.println("相对路径资源:"+url.getPath());
System.out.println("锚点:"+url.getRef()); //锚点
System.out.println("参数:"+url.getQuery()); //?参数: 存在锚点,返回null;不存在,返回正确
//相对路径构建
url = new URL("http://www.baidu.com:80/a/");
url = new URL(url, "b.txt");
System.out.println(url.toString());
}
}
流
InputStream openStream() 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
package com.kennosaur.net.url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;
/**
* 获取资源: 源代码
* InputStream openStream() 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
* @author Administrator
*
*/
public class Url02 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.baidu.com"); //主页默认资源
//获取资源网络流
/*
InputStream is = url.openStream();
byte[] flush = new byte[1024];
int len = 0;
while (-1!=(len=is.read(flush))) {
System.out.println(new String(flush, 0, len));
}
is.close();*/
BufferedReader br = new BufferedReader(
new InputStreamReader(url.openStream(), "utf-8"));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("baidu.html"),"utf-8"));
String msg = null;
while ((msg=br.readLine())!=null) {
// System.out.println(msg);
bw.append(msg);
bw.newLine();
}
bw.flush();
bw.close();
br.close();
}
}