URL编程简介

一、URL类

url是用来描述如何在Internet上进行资源定位的字符串,一个完整的URL由协议、主机名、端口号、文件名、与引用组成。

例如:http://www.sina.com:80/news/index.html

主机名:www.sina.com

端口号:80

访问的文件名:news/index.html

构造方法如下:

URL(String spec)
          根据 String 表示形式创建 URL 对象。
URL(String protocol,String host, int port,String file)
          根据指定 protocolhostport 号和 file 创建 URL 对象。
URL(String protocol,String host, int port,String file,URLStreamHandler handler)
          根据指定的 protocolhostport 号、filehandler 创建URL 对象。
URL(String protocol,String host,String file)
          根据指定的 protocol 名称、host 名称和 file 名称创建 URL。
URL(URL context,String spec)
          通过在指定的上下文中对给定的 spec 进行解析创建 URL。
URL(URL context,String spec,URLStreamHandler handler)
          通过在指定的上下文中用指定的处理程序对给定的 spec 进行解析来创建 URL。

参数含义如下:

*context :在spec为相对URL时解释spec

*handler : 制定上下文的处理器

* host :主机名

* file : 文件路径名

*port : 要使用的端口号

*protocal :要使用的协议

*spec :url字符串

示例代码如下:

public class URLDemo {

	void display(){
		//建立缓冲区
		byte[] buf=new byte[100];
		URL url;
		try {
			//获取用户输入的URL
			int count = System.in.read(buf);
			String addr=new String(buf,0,count);
			url = new URL(addr);
			//打开一个输入流
			InputStream ins = url.openStream();
			BufferedReader bReader = new BufferedReader(new InputStreamReader(ins));
			//读取数据
			String info= bReader.readLine();
			while(info!=null){
				System.out.println(info);
				info=bReader.readLine();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		URLDemo app=new URLDemo();
		app.display();
	}




版权声明:本文为dongxingpeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。