一、用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("來自客戶機的信息:.......");