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();
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值