JAVA中URL的实现,寻址和访问网络资源
2013-03-22 21:36
537 查看
一、用JAVA实现URL
在JAVA中,Java.net包里面的类是进行网络编程的,其中java.net.URL类和java.net.URLConection类使编程者方便地利用URL在Internet上进行网络通信。1、创建URL对象
URL类有多种形式的构造函数:
(1) URL ( String url) //url代表一个绝对地址,URL对象直接指向这个资源,如: URL urll=new URL(http://www.cqwu.edu.cn); (2) URL ( URL baseURL , String relativeURL) // 其中,baseURL代表绝对地址,relativeURL代表相对地址。如: URL urll=new URL(http://www.cqwu.edu.cn); URL lib=new URL(urll , "library / library.asp"); (3) URL ( String protocol , String host , String file) //其中,protocol代表通信协议,host代表主机名,file代表文件名。如: new URL ("http" , www.cqwu.edu.cn, "/ test / test.asp"); (4) URL ( String protocol , String host , int port , String file) URL lib = new URL ("http" , www.cqwu.edu.cn, 80 , "/ test / test.asp");
2、获取URL对象的属性
getDefaultPort(): 返回默认的端口号。
getFile(): 获得URL指定资源的完整文件名。
getHost(): 返回主机名。
getPath(): 返回指定资源的文件目录和文件名。
getPort(): 返回端口号,默认为-1。
getProtocol(): 返回表示URL中协议的字符串对象。
getRef(): 返回URL中的HTML文档标记,即#号标记。
getUserInfo: 返回用户信息。
toString: 返回完整的URL字符串。
二、Internet寻址
java.net包可以用32位int形式来操作32位的IP地址(即Internet主机地址)。类InetAddress实际上是可以把Internet地址换算成代表该地址的对象。Java就是靠这个类来显示Internet地址已经相关信息的。
InetAddress有以下常用方法:
getAddress(): 返回IP地址的字节形式。
getAllByName(): 返回指定主机名的IP地址。
getbyAddress(): 返回指定字节数组的IP地址形式。
getByName(): 返回指定主机名的IP地址对象。
getHostAddress(): 返回主机地址的字符串形式。
getLocalHost(): 返回当前主机名。
hastCode(): 返回InetAddress对象的哈希码。
toString: 返回地址转换成的字符串。
InetAddress类没有提供返回构造函数,所以不能用new()方法来创建它的对象,而只可以调用静态方法getLocalHost()、getByName()、getByAddress()等来生成InetAddress类的实质。
import java.net.*; import java.io.*; public class InetAddDemo //extends Applet { public void testOperate() { try { InetAddress address=InetAddress.getLocalHost(); log("本机地址字符串:"+address.getHostAddress()); log("本机主机名:"+address.getHostName()); log("本机主机名:"+address.getLocalHost()); log("哈希码:"+address.hashCode()); byte b[]=address.getAddress(); System.out.println("字符形式:"+b); log("地址字符串:"+address.toString()); } catch(Exception e) { //e.printStackTrace("不能打开这个URL"); } } public void log(String strInfo) { System.out.println(strInfo); } public static void main(String args[]) { InetAddDemo IAdd=new InetAddDemo(); IAdd.testOperate(); } }
结果:
本机地址字符串:192.9.200.108 本机主机名:s5 本机主机名:s5/192.9.200.108 哈希码:-1073100692 字符形式:[B@f4a24a 地址字符串:s5/192.9.200.108
有两种方法可以用来访问Internet。一是利用URL类的openStream()方法;二是使openConnection()方法创建一个URLConnection类的对象。其中,方法openStream()与指定的URL建立连接并返回InputStream类的对象,以从这一连接中读取数据。
import java.net.*; import java.io.*; public class ReadURL { public static void main(String args[]) throws Exception { try { URL url=new URL("http://www.baidu.com"); InputStreamReader isr=new InputStreamReader(url.openStream()); BufferedReader br=new BufferedReader(isr); String str; while((str=br.readLine())!=null) { System.out.println(str); } br.close(); isr.close(); } catch(Exception e) { System.out.println(e); } } }
结果:
<html><head><title>百度一下,你就知道 </title><meta http-equiv=Content-Type content="text/html;charset=gb2312"> <style>body{}{margin:4px 0 4px 0;}img{}{border:0}td,p{}{font-size:12px}p{}{width:600px;margin:0;padding:0}.kw{}{font-family:Verdana;font-size:16px;height:1.78em;padding-top:2px;} #b {}{width:600px;height:30px;padding-top:4px;color:#77c;font-size:12px;font-family:Arial}#b a{}{color:#77c;font-size:12px} #usrbar{}{padding-right:10px;line-height:19px;font-size:12px;font-family:Arial;text-align:right;white-space:nowrap;margin-bottom:3px !important;margin-bottom:10px;} .sb{}{height:2em;width:5.6em;font-size:14px;}#km{}{font-size:14px;height:50px;}a{}{font-family:arial}#km a{}{font-family:宋体} #l{}{font-size:14px;font-family:arial;width:600px;text-align:left;margin-bottom:5px} #l tr td{}{text-align:left;font-family:arial;} #l tr td div{}{font-size:14px;margin-left:92px;width:22.1em;text-align:center;}</style><script> function h(obj,url){obj.style.behavior='url(#default#homepage)';obj.setHomePage(url);} function g(){var ls=location.search;if(ls.indexOf("q=")!=-1){try{var q=(ls.match(new RegExp("q=[^&$]*")).toString());document.f.wd.value=decodeURIComponent(q.substr(2));}catch(e){}}} function s(o,p){if(document.f.wd.value.length>0){var oh=o.href;var qw=encodeURIComponent(document.f.wd.value);if(oh.indexOf("q=")!=-1){o.href=oh.replace(new RegExp("q=[^&$]*"),"q="+qw);}else{var s=p?"&":"?";o.href=o.href+s+"q="+qw};}}</script></head> <body text=000000 link=0000cc vlink=0000cc alink=ff6600> <div id="usrbar"><script language="JavaScript">document.write('<a href="http://passport.baidu.com/?login&tpl=mn&u='+escape(location.href)+'">登录</a>');</script></div> <center><a href=http://hi.baidu.com/baidu target=_blank><img src=http://www.baidu.com/img/logo.gif width=174 height=59 alt="点此进入 百度空间" ></a><br><br><br><br> <table border="0" cellpadding="0" cellspacing="0" id="l" ><tr><td><div><a href="http://news.baidu.com" onclick="return s(this);">新 闻</a> <strong>网 页</strong> <a href="http://post.baidu.com/f?ct=486539264&cm=58580&tn=baiduForumIndex" onclick="return s(this,1);">贴 吧</a> <a href="http://zhidao.baidu.com" onclick="return s(this);">知 道</a> <a href="http://mp3.baidu.com" onclick="return s(this);">MP3</a> <a href="http://image.baidu.com" onclick="return s(this);">图 片</a></div></td></table> <table width=600 border=0 cellpadding=0 cellspacing=0><tr valign=top><td width=92></td><td height=62> <form name=f action=/s><input type=text name=wd class=kw size=36 maxlength=100><script>document.f.wd.focus();g()</script><input type=hidden name=cl value=3> <input type=submit value=百度一下 class=sb><br><br></form></td><td width=100><a href=/search/jiqiao.html>帮助</a><br><a href=/gaoji/advanced.html>高级</a></td></tr></table> <p id=km> <a href="http://hi.baidu.com/">空间</a> | <a href="http://www.baidu.com/more/">更多>></a></p> <p style=height:60px;> </p> <p style=height:30px;><a onclick="h(this,'http://www.baidu.com')" href=http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com>把百度设为首页</a></p> <p style=height:14px;><a href=http://jingjia.baidu.com/>企业推广</a> | <a href=http://top.baidu.com/>搜索风云榜</a> | <a href=/home.html>关于百度</a> | <a href=http://ir.baidu.com>About Baidu</a></p><p id=b>©2007 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://www.miibeian.gov.cn/ target=_blank>京ICP证030173号</a> <a href=http://www.hd315.gov.cn/beian/view.asp?bianhao=010202001092500412><img src=http://gimg.baidu.com/img/gs.gif></a></p></center></body></html>
上例首先创建URL对象url,并在其基础上打开输入流获取InputStreamReader对象,再由此对象创建BufferedReader对象br,从br中读取数据即可得到url所指定的资源文件。
上面的openStream()方法只能读取网络资源,若要既能读取又能发送数据,则要用到URL类的openConnection()方法来创建一个 URLConnection类的对象,此对象在本地机和URL指定的远程节点建立一条HTTP协议的数据通道,可进行双向数据传输。
类URLConnection提供了很多设置和获取连接参数的方法,最常用到的是getInputStream()和getOutputStream()方法,如:
URL sum=new URL("http://java.sum.com/cgi-bin/backwards"); URLConnection suncon=buaa.openConnection(); sumcon.setDoOutput(true); DataInputStream dis=new DataInputStream(suncon.getInputStream()); PrintStream ps=new PrintStream(suncon.getOutputStream()); String str=dis.readLine(); ps.println("来自客户机的信息:.......");
转自:http://www.blogjava.net/baoyaer/articles/120422.html
作者:baoyaer
相关文章推荐
- crawler_基础之_java.net.HttpURLConnection 访问网络资源
- 转载 通过JAVA语言实现使用URL访问网络资源
- Java 网络编程(三) 创建和使用URL访问网络上的资源
- Java 网络编程(三) 创建和使用URL访问网络上的资源
- Java 网络编程(三) 创建和使用URL访问网络上的资源
- Java实现代理ip访问网络的实现方式之Java实现切换ip访问网络资源
- Android上Java网络资源访问(二)使用HttpURLConnection多线程下载
- 用C实现一个访问url资源下载的小例子
- Android开发之使用URL访问网络资源
- 疯狂安卓实训 第13.2.1讲 使用URL和URLConnection访问网络资源
- HttpUrlConnection实现多线程下载网络资源
- 使用URL访问网络资源
- Java使用URL读取网络图片资源 并保存在本地
- Java实现获取Web上所有路径下资源文件的URL地址
- PHP CURL 实现并发访问网络资源
- Android中实现下载URL地址的网络资源的实例分享
- 使用URL访问网络资源
- Java实现访问指定url,并在指定时长后自动关闭浏览器
- 创建和使用URL访问网络资源
- Java访问网络url,获取网页的html代码