Java用Socket類實(shí)現(xiàn)HTTP協(xié)議客戶端應(yīng)用_第1頁(yè)
Java用Socket類實(shí)現(xiàn)HTTP協(xié)議客戶端應(yīng)用_第2頁(yè)
Java用Socket類實(shí)現(xiàn)HTTP協(xié)議客戶端應(yīng)用_第3頁(yè)
Java用Socket類實(shí)現(xiàn)HTTP協(xié)議客戶端應(yīng)用_第4頁(yè)
Java用Socket類實(shí)現(xiàn)HTTP協(xié)議客戶端應(yīng)用_第5頁(yè)
已閱讀5頁(yè),還剩2頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、java:用socket類實(shí)現(xiàn)http協(xié)議客 戶端應(yīng)用http客戶端程序已集成在java語(yǔ)言屮,可以通過(guò)urlconnection類調(diào)用。遺憾 的是,由于su"沒(méi)有公布htlp客戶程序的源碼,它實(shí)現(xiàn)的細(xì)節(jié)仍是一個(gè)謎。木文 根據(jù)http協(xié)議規(guī)范,用java. net. socket類實(shí)現(xiàn)一個(gè)http協(xié)議客戶端程序。1. socket 類:了解tcp/tp協(xié)議集通信的讀者知道,協(xié)議間的通信是通過(guò)sockel完成的。在 java, net包中,socket類就是對(duì)socket的具體實(shí)現(xiàn)。它通過(guò)連接到主機(jī)后,返 回一個(gè)1/0流,實(shí)現(xiàn)協(xié)議間的信息交換。2. http協(xié)議http協(xié)議同其它tcp

2、/ip協(xié)議集中的協(xié)議一樣,是遵循客戶/服務(wù)器模型工作的。 客戶端發(fā)往服務(wù)端的信息格式如下: 請(qǐng)求方法urlhttp協(xié)議的版木號(hào) 提交的元信息*空彳亍*實(shí)體 請(qǐng)求方法是對(duì)這次連接工作的說(shuō)明,目前http協(xié)議已經(jīng)發(fā)展到1.1版,它包括 get、head、post、delete> options、trace、put七種。元信息是關(guān)于當(dāng)前請(qǐng)求的信 息。通過(guò)分析元信息,可以檢查實(shí)體數(shù)據(jù)是否完整,接收過(guò)程是否出錯(cuò),類型是否匹配 等。元信息的引入使http協(xié)議通信更加穩(wěn)妥可靠。實(shí)體是請(qǐng)求的具體內(nèi)容。將上述報(bào)文發(fā)往web服務(wù)器,如果成功,應(yīng)答格式如下:http協(xié)議的版木號(hào)應(yīng)答狀態(tài)碼應(yīng)答狀態(tài)碼說(shuō)明 接收的

3、元信息*空彳亍*實(shí)體 以上報(bào)文發(fā)向客戶端,并且接收成功,彼此間關(guān)閉連接,完成一次握手。卜而用最常用的get方法,來(lái)說(shuō)明具體的報(bào)文應(yīng)用gethttp:/www. youhost. comhttp/1. 0accept:www/source;text/html;image/gif;image/jpeg;*/* uscr_agcnt:myagcnt這個(gè)報(bào)文是向www. youhost. com主機(jī)請(qǐng)求一個(gè)缺省html文檔??蛻舳薶ttp協(xié)議 版木號(hào)是1.0版,元信息包括可接收的文件格式,用戶代理,每一段之間用回車換行 符分隔,最后以一個(gè)空行結(jié)束。發(fā)向服務(wù)器后,如杲執(zhí)行過(guò)程正常,服務(wù)器返回以下 代碼:

4、http/1. 12000kdatc:tuc, 14scpl99902:19:57gmtserver:apache/l. 2. 6connection:closecontent-type:text/html*空彳亍*<html><hcad>. . . </hcad><body>. . . </body></html>http/1. 1表示這個(gè)http服務(wù)器是1. 1版,200是服務(wù)器對(duì)客戶請(qǐng)求的應(yīng)答狀態(tài) 碼,0k是對(duì)應(yīng)答狀態(tài)碼的解釋,之后是這個(gè)文檔的元信息和文檔正文。(相關(guān)應(yīng)答狀態(tài) 碼和元信息的解釋請(qǐng)參閱inetrnet標(biāo)

5、準(zhǔn)草案:rfc2616)。http. javaimportjava. net. *;importjava. io. *;importjava. util. properties;importjava. util. enumeration;publicclasshttpprotectedsocketclient;protectedbufferedoutputstreamsender;protec tedbufferedtnputstreeimrecei ver;protcctcdbytcarray in putstrcamb)rtcstrcam;protectedurltarget;privat

6、eintresponsecode=-l; privatestringresponsemessage二;privatestringserverversion=/z,/;privatepropertiesheader=newproperties(); publichttpo publichttp(stringurl)get(url);/*get方法根據(jù)url,會(huì)請(qǐng)求文件、數(shù)據(jù)庫(kù)查詢結(jié)果、程序運(yùn)行結(jié)果等多種內(nèi)容 */publi cvoi dget(stri ngurl)try checkhttp(url); openserver (target. gethost(), target. getport

7、(); stringcmd=,zget/z+geturlformat (target) +z,http/1. 0rn,/ +getbaseheads() +rn;sendmcssagc(emd); receivemessage();catch (protocolexceptionp)p. printstacktrace ();return; catch (unknowniiostexccptione) e. printstacktrace ();return;catch(ioexceptioni)i.printstacktrace();return;/*iiead方法只請(qǐng)求url的元信息,不包

8、括url本身。若懷疑本機(jī)和服務(wù)器上的*文件相同,用這個(gè)方法檢查最快捷冇效。*/publicvoidhead(stringurl) try checkhttp(url);openserver (target gethost(), target getport(); stringcmd=/head,+geturlformat (target) +/zhttp/1. 0rn,z +getbaseheads()+r; sendmessage(emd);rcccivcmcssagco ;catch (protocolexceptionp) p. printstacktrace ();return;cat

9、ch(unknownhostexceptione) e. printstacktrace ();return;catch(toexceptioni)i. printstacktracc ();return;/*post方法是向服務(wù)器傳送數(shù)據(jù),以便服務(wù)器做出相應(yīng)的處理。例如網(wǎng)頁(yè)上常用 的*提交表格。*/publicvoidpost (stringurl, stringeontent)try checkhttp (url);openserver(target. gethost(), target. getport ();stri ngcmd=/zpost,z+geturlformat (targe

10、t) +,zhttp/1. orn"+getbaseheeids (); cmd+二content-typc:application/x-www-fonn-urlcncodcdrn; cmd+二content-length:+content length () +,zrnrnz,;cmcl+二 content+rrt;sendmessage(emd);recei vemessageo ;catch (protocolexccptionp) p. printstacktrace ();return;catch(unknownhostexceptione)e. printstacktra

11、ce();return;catch(loexceptioni) i. printstacktrace ();return;ijprotectedvoidcheckhttp(stringurl)throwsprotocolexception try urltarget=newurl(url);if (targct二二null|target gctprotocol () touppercasc() equals("http") thrownewprotocolexception (z,這不是 http i辦議“);this, target二target;catch (maifo

12、rmedurlexcept ionm) thrownewprotocolexception (辦議格式錯(cuò)誤);/*與web服務(wù)器連接。若找不到web服務(wù)器,inetaddress會(huì)引發(fā) unknownhostexception*異常。若socket連接失敗,會(huì)引發(fā)ioexception異常。*/protectedvoi dopenserver(stri nghost, i ntport)throws unknowniiostexccption,ioexccption header, clear (); responsemessage二;responsecode=-l;try if(cli en

13、t!二nul1)closeserver();if(bytcstrcam!二null) bytestream. close();bytestream=null; inetaddressaddress=inetaddress. getbyname(host);cl ient二newsocket (address, port二二t?80:port);sen dor 二 nc wbuf fcrcdoutputstrcam (die nt. gctoutputstrcam (); receiver=newbufferedlnputstream(client. getlnputstreamo); catc

14、h (unknownhostexceptionu) throwu;catch(toexceptioni) throwi;/*關(guān)閉與web服務(wù)器的連接*/ protcctedvoideloscscrvcr()throwsioexccption if (client-null) return;try client, close () ; sender, close () ;receiver, close (); catch(toexceptioni) throwi;client二null;sender=null;receiver=null;protcctcdstringgcturlformat(u

15、rltargct) stringspec=,zhttp: /,z+target. gethost (); if (target. getport () !=-l) spec+二:z/+target. getport ();returnspec+=target. getfile(); /*向web服務(wù)器傳送數(shù)據(jù)*/ protcctcdvoidscndmcssogc(stringdata)throwsioexccption sender, write (data. getbytes (), 0, data, length (); sender, flush ();/*接收來(lái)自web服務(wù)器的數(shù)據(jù)*/

16、 protcctcdvoidrcccivcmcssagc()throwsioexccption bytedata=newbyte1024;intcount=0;intword=-l; 解析第一行 while(word=rccciver. read() !=1) i f (word=,r |word=,n,) word二:receiver, read ();if (word二二'rf ) word二receiver, read ();break;ijif (count=data. length)dataaddcapacity(data); datacount+二(byte)word;st

17、ringmessage=newstring(data, 0, count);intmark=mcssagc. indcxof(32); serverversion=message. substring(0, mark);while(mark<message. length()&&message. charat(mark+1)=32)mark+; responsecode二integer. parselnt(message, substring(mark+l, mark+=4); responsemessage二message, substring(mark, messag

18、e, lenth(). trim();應(yīng)答狀態(tài)碼和處理請(qǐng)讀者添加 switch(responsecode) casedoo: thrownewioexception (錯(cuò)誤請(qǐng)求);casc404:thrownewf i1enotfoundexcept i on(geturlformat(target);case503: thrownewioexception(服務(wù)器不可用); if (word=-l) throwncwprotocolexccption ("信息接收異常終止); intsymbol=-l;count=0;解析兀信息while (word!=,r &&w

19、ord!=,n,&&word>-l) if (word=,t,) word=32;if (count二二data, length)data=addcapaci ty(data); datacount+ = (byte) word;parsclinc: while(symbol=receiver. read()>-l) switch(symbol)case' t :symbol=32;break;case" r :case" n":word二receiver. read();if (symbol二二'r,&&

20、;word=,n,) word二receiver, read ();if (word二二'r )word=receiver. read();ijif (word=" r" |word=" n" |word>32)breakparseline; symbol=32;break;if (co unt 二二 deitei. le n£t h) data=addcapac ity (data); datacount+二(byte) symbol;word=-l; message=newstring(data, 0, count);mark

21、=mcssagc. indcxof c :,);stringkey二null;if (mark>0)key=message. substring(0, mark);mark+;whi1e (mark<message. 1ength()&&message. charat(mark)<=32)mark+; stringvalue=mcssagc. substring(mark, message, length();header.put (key, value);count=0;/獲得正文數(shù)據(jù)while(word=rccciver. read()!=1)if (co

22、unt=data. length)dataaddcapacity(data); datacount+二(byte)word;if (count>0)bytestream=newbytearraytnputstream(data, 0, count); data=null;closeserver ();publicstringgetresponsemessage() returnresponsemessage;publicintgctrcsponsccodco returnresponsecode;publicstringgetserverversion() returnserverversi on;publicinputstreamgetinputstream() returnbvtestream;publicsynchronizedstringgetheaderkey(inti) if(i>二header, size()returnnull;enumerationenum二header. propertynames();stringkey=nul1; for(intj=0;j<=i;j+) key= (string)enum. nextelement(); returnkey;publicsync

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論