1、URL(Uniform Resource Locator)统一资源定位符,表示Internet上某一资源的地址
如我们的博客地址
2、URL由俩部分组成:协议名称和资源名称,中间用冒号隔开。
如: http://www.baidu.com
http表示协议名称
www.baidu.com甚至加上端口号都统称为资源名称
3、在java.net包中,提供了URL类来表示URL。
java中URL的方法
构造方法
URL(String spec) 根据String表示形式创建URL对象表示相应的地址
URL(String protocol ,String host, int port ,String file)根据协议、主机名、端口号、文件信息
URL(URL context,String spec)通过在指定的上下文中对给定的spec进行解析创建URL
测试:
public static void main(String[] args) {
try {
//创建一个URL实例
URL imooc =new URL("http://www.imooc.com");
//根据已存在的URL去创建一个新的URL
//?后面表示参数,#后面表示锚点
URL url=new URL(imooc,"/index.html?username=tom#test");
System.out.println("协议:"+url.getProtocol());
System.out.println("主机:"+url.getHost());
System.out.println("端口号:"+url.getPort());
System.out.println("文件路径:"+url.getPath());
System.out.println("文件名:"+url.getFile());
System.out.println("相对路径:"+url.getRef());
System.out.println("查询字符串:"+url.getQuery());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
测试结果:
协议:http
主机:www.imooc.com
端口号:-1
文件路径:/index.html
文件名:/index.html?username=tom
相对路径:test
查询字符串:username=tom
使用URL读取网页内容
1、通过URL对象的openStream()方法可以得到指定资源的输入流。
2、通过输入流可以读取、访问网络上的数据。
测试:
public static void main(String[] args) {
try {
//创建一个URL实例
URL url = new URL("http://www.baidu.com");
//通过URL的openStream方法获取URL对象所表示的资源扥字节输入流
InputStream is = url.openStream();
//将字节输入流转换为字符输入流
InputStreamReader isr= new InputStreamReader(is,"utf-8");
//为字符输入流添加缓冲
BufferedReader br = new BufferedReader(isr);
String data =br.readLine();
while(data!=null)
{
System.out.println(data);
data=br.readLine();
}
br.close();
isr.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}