java network programming 笔记
n5
三 利用url类获取数据
chapter 7 retrieving data with urls
1 建立url对象
当jvm不支持url的协议时抛出malformedurlexception
(1)public url(string url) throws malformedurlexception
(2)public url(string protocol, string hostname, string file) throws malformedurlexception
此构造器设置port为-1,所以协议的默认端口将被使用。
file参数应该以”/”开始,包含一个路径,文件名,和一个可选的锚点
例如: url u = new url(“http”,”www.eff.org”,”/blueribbon.html#intro”) ;
(3)public url(string protocol,string host, int port, string file) throws malformedurlexception
可以指定端口,其他和第二个构造器相同
(4)public url(url base,string relative) throws malformedurlexception
从一个相对的url地址和一个base url对象创建一个绝对url对象
例如:
try{
url u1 = new url(“http://www.myweb.com/java/index.html”) ;
url u2 = new url(u1,”test.html”) ;
}
catch(malformedurlexception e){}
去掉u1的文件名,然后加上新文件名test.html,就构成了u2
2得到url的组成
getfile() 返回总的路径(并非文件名)即为url中从第一个”/”开始到”#”为止的内容。如果没有file部分,java1.3返回一个空字符串,java1.1,1.2返回”/”
gethost() 返回主机名,不包含user:user这样的用户信息
getport() 如果url中没指定端口,则返回-1
getprotocol()
getref() 返回指定的锚点,如果没有锚点返回null
//since java1.3
getquery()
getpath() 和getfile()完全相同
getuserinfo()
getauthority()
3 从url得到数据
(1) public final inputstream openstream() throws ioexception
打开url,得到一个inputstream得到数据
(2) public urlconnection openconnection() throws ioexception
打开url,得到一个urlconnection对象,urlconnection对象表示网络资源的一个开放连接。当想要直接与服务器通讯时可使用该方法。urlconnection可以得到服务器发送的任何东西,而不仅仅是文档本身。而且还可以写数据。
(3) public final object getcontent() throws ioexception
将从url下载来的数据看作一个对象,比如图片,文本,声音,或一个inputstream对于不能理解的对象。可以用instance of判断到底是哪种对象,并cast为该对象。
(4) public final object getcontent(class[] classes) throws ioexception //java1.3
可指定哪些种类的class被返回。该方法按照classes数组的顺序依次尝试返回内容。
4 工具方法
public boolean samefile(url other)
测试两个url是否指向同一个文件。
public string toexternalform()
返回一个人类可读的string表示url,和tostring()方法等同。因此不常用这个方法。
5 public boolean equals(object o)
相等的含义:object o也是一个url对象,两个url都指向同一个file(samefile()定义的),并且两个url有相同的引用或都是null。
