Http用戶端程式已整合在Java語言中,可以通過URLConnection類調用。遺憾的
是,由於SUN沒有公布Http客戶程式的源碼,它實現的細節仍是一個謎。本文根據HTTP
協議規範,用Java.net.Socket類實現一個HTTP協議用戶端程式。
1.Socket類:
瞭解TCP/IP協議集通訊的讀者知道,協議間的通訊是通過Socket完成的。在
Java.net包中,Socket類就是對Socket的具體實現。它通過串連到主機後,返回一個
I/O流,實現協議間的資訊交換。
2.HTTP協議
HTTP協議同其它TCP/IP協議集中的協議一樣,是遵循客戶/伺服器模型工作的。客
戶端發往服務端的資訊格式如下:
------------------------------
要求方法URLHTTP協議的版本號碼
提交的元資訊
**空行**
實體
------------------------------
要求方法是對這次串連工作的說明,目前HTTP協議已經發展到1.1版,它包括GET、
HEAD、POST、DELETE、OPTIONS、TRACE、PUT七種。元資訊是關於當前請求的資訊。通
過分析元資訊,可以檢查實體資料是否完整,接收過程是否出錯,類型是否匹配等。元
資訊的引入使HTTP協議通訊更加穩妥可靠。實體是請求的具體內容。
將上述報文發往Web伺服器,如果成功,應答格式如下:
--------------------------------
HTTP協議的版本號碼應答狀態代碼應答狀態代碼說明
接收的元資訊
**空行**
實體
--------------------------------
以上報文發向用戶端,並且接收成功,彼此間關閉串連,完成一次握手。
下面用最常用的GET方法,來說明具體的報文應用
----------------------------------
GEThttp://www.youhost.comHTTP/1.0
accept:www/source;text/html;image/gif;image/jpeg;*/*
User_Agent:myAgent
**空行**
-----------------------------------
這個報文是向www.youhost.com主機請求一個預設HTML文檔。用戶端HTTP協議版本
號是1.0版,元資訊包括可接收的檔案格式,使用者代理程式,每一段之間用斷行符號分行符號分
隔,最後以一個空行結束。發向伺服器後,如果執行過程正常,伺服器返回以下代碼:
------------------------------------
HTTP/1.1200OK
Date:Tue,14Sep199902:19:57GMT
Server:Apache/1.2.6
Connection:close
Content-Type:text/html
**空行**
<html><head>...</head><body>...</body></html>
------------------------------------
HTTP/1.1表示這個HTTP伺服器是1.1版,200是伺服器對客戶請求的應答狀態代碼,OK
是對應答狀態代碼的解釋,之後是這個文檔的元資訊和文檔本文。(相關應答狀態代碼和元
資訊的解釋請參閱Inetrnet標準草案:RFC2616)。
3.HTTP用戶端程式:
importjava.net.*;
importjava.io.*;
importjava.util.Properties;
importjava.util.Enumeration;
publicclassHttp{
protectedSocketclient;
protectedBufferedOutputStreamsender;
protectedBufferedInputStreamreceiver;
protectedByteArrayInputStreambyteStream;
protectedURLtarget;
privateintresponseCode=-1;
privateStringresponseMessage="";
privateStringserverVersion="";
privatePropertiesheader=newProperties();
publicHttp(){}
publicHttp(Stringurl){
GET(url);
}
/*GET方法根據URL,會請求檔案、資料庫查詢結果、程式運行結果等多種內容*/
publicvoidGET(Stringurl){
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort());
Stringcmd="GET"+getURLFormat(target)+"HTTP/1.0/r/n"
+getBaseHeads()+"/r/n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolExceptionp){
p.printStackTrace();
return;
}catch(UnknownHostExceptione){
e.printStackTrace();
return;
}catch(IOExceptioni)
i.printStackTrace();
return;
}
}
/*
*HEAD方法只請求URL的元資訊,不包括URL本身。若懷疑本機和伺服器上的
*檔案相同,用這個方法檢查最快捷有效。
*/
publicvoidHEAD(Stringurl){
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort());
Stringcmd="HEAD"+getURLFormat(target)+"HTTP/1.0/r/n"
+getBaseHeads()+"/r/n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolExceptionp){
p.printStackTrace();
return;
}catch(UnknownHostExceptione){
e.printStackTrace();
return;
}catch(IOExceptioni)
i.printStackTrace();
return;
}
}
/*
*POST方法是向伺服器傳送資料,以便伺服器做出相應的處理。例如網頁上常用的
*提交表格。
*/
publicvoidPOST(Stringurl,Stringcontent){
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort());
Stringcmd="POST"+getURLFormat(target)+"
HTTP/1.0/r/n"+getBaseHeads();
cmd+="Content-type:application/x-www-form-urlencoded/r/n";
cmd+="Content-length:"+content.length()+"/r/n/r/n";
cmd+=content+"/r/n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolExceptionp){
p.printStackTrace();
return;
}catch(UnknownHostExceptione){
e.printStackTrace();
return;
}catch(IOExceptioni)
i.printStackTrace();
return;
}
}
protectedvoidcheckHTTP(Stringurl)throwsProtocolException{
try{
URLtarget=newURL(url);
if(target==null||!target.getProtocol().toUpperCase().equals("HTTP"))
thrownewProtocolException("這不是HTTP協議");
this.target=target;
}catch(MalformedURLExceptionm){
thrownewProtocolException("協議格式錯誤");
}
}
/*
*與Web伺服器串連。若找不到Web伺服器,InetAddress會引發UnknownHostException
*異常。若Socket串連失敗,會引發IOException異常。
*/
protectedvoidopenServer(Stringhost,intport)throws
UnknownHostException,IOException{
header.clear();
responseMessage="";responseCode=-1;
try{
if(client!=null)closeServer();
if(byteStream!=null){
byteStream.close();byteStream=null;
}
InetAddressaddress=InetAddress.getByName(host);
client=newSocket(address,port==-1?80:port);
sender=newBufferedOutputStream(client.getOutputStream());
receiver=newBufferedInputStream(client.getInputStream());
}catch(UnknownHostExceptionu){
throwu;
}catch(IOExceptioni){
throwi;
}
}
/*關閉與Web伺服器的串連*/
protectedvoidcloseServer()throwsIOException{
if(client==null)return;
try{
client.close();sender.close();receiver.close();
}catch(IOExceptioni){
throwi;
}
client=null;sender=null;receiver=null;
}
protectedStringgetURLFormat(URLtarget){
Stringspec="http://"+target.getHost();
if(target.getPort()!=-1)
spec+=":"+target.getPort();
returnspec+=target.getFile();
}
/*向Web伺服器傳送資料*/
protectedvoidsendMessage(Stringdata)throwsIOException{
sender.write(data.getBytes(),0,data.length());
sender.flush();
}
/*接收來自Web伺服器的資料*/
protectedvoidreceiveMessage()throwsIOException{
bytedata[]=newbyte[1024];
intcount=0;
intword=-1;
//解析第一行
while((word=receiver.read())!=-1){
if(word=='/r'||word=='/n'){
word=receiver.read();
if(word=='/n')word=receiver.read();
break;
}
if(count==data.length)data=addCapacity(data);
data[count++]=(byte)word;
}
Stringmessage=newString(data,0,count);
intmark=message.indexOf(32);
serverVersion=message.substring(0,mark);
while(mark<message.length()&&message.charAt(mark+1)==32)mark++;
responseCode=Integer.parseInt(message.substring(mark+1,mark+=4));
responseMessage=message.substring(mark,message.length()).trim();
//應答狀態代碼和處理請讀者添加
switch(responseCode){
case400:
thrownewIOException("錯誤請求");
case404:
thrownewFileNotFoundException(getURLFormat(target));
case503:
thrownewIOException("伺服器不可用");
}
if(word==-1)thrownewProtocolException("資訊接收異常終止");
intsymbol=-1;
count=0;
//解析元資訊
while(word!='/r'&&word!='/n'&&word>-1){
if(word=='/t')word=32;
if(count==data.length)data=addCapacity(data);
data[count++]=(byte)word;
parseLine:{
while((symbol=receiver.read())>-1){
switch(symbol){
case'/t':
symbol=32;break;
case'/r':
case'/n':
word=receiver.read();
if(symbol=='/r'&&word=='/n'){
word=receiver.read();
if(word=='/r')word=receiver.read();
}
if(word=='/r'||word=='/n'||word>32)breakparseLine;
symbol=32;break;
}
if(count==data.length)data=addCapacity(data);
data[count++]=(byte)symbol;
}
word=-1;
}
message=newString(data,0,count);
mark=message.indexOf(':');
Stringkey=null;
if(mark>0)key=message.substring(0,mark);
mark++;
while(mark<message.length()&&message.charAt(mark)<=32)mark++;
Stringvalue=message.substring(mark,message.length());
header.put(key,value);
count=0;
}
//獲得本文資料
while((word=receiver.read())!=-1){
if(count==data.length)data=addCapacity(data);
data[count++]=(byte)word;
}
if(count>0)byteStream=newByteArrayInputStream(data,0,count);
data=null;
closeServer();
}
publicStringgetResponseMessage(){
returnresponseMessage;
}
publicintgetResponseCode(){
returnresponseCode;
}
publicStringgetServerVersion(){
returnserverVersion;
}
publicInputStreamgetInputStream(){
returnbyteStream;
}
publicsynchronizedStringgetHeaderKey(inti){
if(i>=header.size())returnnull;
Enumerationenum=header.propertyNames();
Stringkey=null;
for(intj=0;j<=i;j++)
key=(String)enum.nextElement();
returnkey;
}
publicsynchronizedStringgetHeaderValue(inti){
if(i>=header.size())returnnull;
returnheader.getProperty(getHeaderKey(i));
}
publicsynchronizedStringgetHeaderValue(Stringkey){
returnheader.getProperty(key);
}
protectedStringgetBaseHeads(){
Stringinf="User-Agent:myselfHttp/1.0/r/n"+
"Accept:www/source;text/html;image/gif;*/*/r/n";
returninf;
}
privatebyte[]addCapacity(byterece[]){
bytetemp[]=newbyte[rece.length+1024];
System.arraycopy(rece,0,temp,0,rece.length);
returntemp;
}