Import java.net. *; import java.io. *; import java.util.properties; import java.util.enumeration;
/ ** HTTP client program is integrated in the Java language, you can call via the URLConnection class. Unfortunately, because Sun does not publish the source code of the HTTP client, the details of its implementation are still a mystery. This article implements an HTTP protocol client program in accordance with the Java.Net.Socket class in accordance with the HTTP protocol specification.
1. Socket class: Understand the readers of the TCP / IP protocol set communication, communication between the protocols is done through socket. In a java.net package, the Socket class is the specific implementation of Socket. After connecting to the host, it returns an I / O stream to implement information exchange between protocols.
2. The HTTP protocol The HTTP protocol is the same as the protocol in other TCP / IP protocols, which follows the client / server model. The information format of the client is as follows: ----------------------------- Request method URL HTTP protocol version number submitted Met information ** blank line ** entity ---------------------------- request method is a description of this connection work, At present, the HTTP protocol has also developed to version 1.1, including GET, HEAD, POST, DELETE, OPTIONS, TRACE, PUT seven. The meta information is information about the current request. Through analysis element information, you can check if the entity data is complete, whether the receiving process is wrong, whether the type matches the same. The introduction of meta information makes HTTP protocol communications more secure. The entity is the specific content of the request. Send the above message to the web server, if successful, the answer format is as follows: ------------------------------ HTTP protocol Version number response status code response status code Description received meta information ** blank ** entity ----------------------------- --- The above newspaper is sent to the client, and the reception is successful, and the connection is turned off at each other, and the handshake is completed. The following uses the most common GET method to clear the specific packet application ------------------------------ Get http://www.youhost.com http / 1.0accept: www / source; text / html; image / gif; image / jpeg; * / * user_agent: myagent ** blank ** ---------- -------------------------- this message is to request a default HTML document to www.youhost.com host. The client HTTP protocol version number is version 1.0, and the metadet information includes the received file format, the user agent, and each segment is separated by the carriage return line, and finally ends with an idlore. After the server is sent, if the execution process is normal, the server returns the following code: --------------------------------- -HTTP / 1.1 200 Okdate: Tue, 14 Sep 1999 02:19:57 gmtserver: Apache / 1.2.6connection: CloseContent-type: text / html ** blank line ** ......------ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The code, OK is an explanation of the reply status code, which is then the metadata and the text of the document. (Explanation of related response status codes and meta information, please refer to the INETRNET standard draft: RFC2616).
Note: Three ways to achieve GET, HEAD, and POST are implemented in the program. Several other due to uncommon usage, temporarily ignored.
* / Public class Http {protected Socket client;?? Protected BufferedOutputStream sender;? Protected BufferedInputStream receiver;? Protected ByteArrayInputStream byteStream;? Protected URL target;? Private int responseCode = -1;? Private String responseMessage = "" ;? private String Serverversion = "" ;? private property () ;? public http () {}
PUBLIC HTTP (STRING URL) {? get (url);?}
? / * GET method according to the URL, will request file, database query results, program operation results, etc. * /? Public void get (string url) {??? ??? checkhttp (url); ??? OpenServer (), target.get (); ??? string cmd = "get" getURLFormat (Target) "http / 1.0 / r / n" getBaseheads () "/ r / n"; ??? SendMessage (); ??? ReceiveMessage (); ??} ?? catch (protocolexception p) {??? p.PrintStackTrace (); ??? Return; ??} ?? Catch (UnknownHOSTEXCEPTION E) {??? E.PrintStackTrace (); ??? Return; ??} ?? ooException i) {??? I.printStackTrace (); ??? Return; ??}?
• / *? * Head method only requests meta information of the URL, does not include the URL itself. If you doubt the same system and server? * Files, use this method to check the fastest and effective. ? * /? public void head (string url) {?? try {??? checkhttp (url); ??? OpenServer (), target.getport (); ??? String cmd = "Head " getURLFORMAT (TARGET) " http / 1.0 / r / n " getBaseheads () " / r / n "; ??? ReceiveMessage (); ??} ?? catch (); ??} ?? catch Protocolexception P) {??? p.PrintStackTrace (); ??? Return; ??} ?? carat (unknownhostexception e) {??? E.PrintStackTrace (); ??? Return; ??} ?? Catch ( IOEXCEPTION I) {??? I.PrintStackTrace (); ??? Return; ??}?
• / *? * The POST method is to transfer data to the server so that the server makes the corresponding process. Such as commonly used on the web page * Submit the form. ? * /? public void post (string url, string content) {?? try {??? checkhttp (url); ??? OpenServer (), target.getport (); ??? String cmd = "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 (protocolexception p) {??? p.PrintStackTrace (); ??? Return; ??} ?? Catch (unknownhostException e) {??? .printstackTrace (); ??? Return; ??} ?? ooException i) {??? I.PrintStackTrace (); ??? Return; ??}?
? protected sharp checkhttp (string url) throws protocolexception {?? try {??? url target = new url (url); ??? if (target == null ||! target.getProtocol (). Touppercase (). Equals ("Http")) {???? throw new protocolexception ("This is not an HTTP protocol"); ???} ??? this.target = target; ??} ?? catch (Malformedurlexception M) {??? Throw new protocolexception ("protocol format error");??}?}
? / *? * Connect to the web server. If you can't find a web server, inetaddress will trigger unknownhostException? * Exception. If the Socket connection fails, IOEXCEPTION exception will be triggered. ? * /? protected void OpenServer (String Host, INT port) throws unknownhostexception, iexception {?? header.clear (); ?? responsemessage = "; ?? responsecode = -1;
?? if (client! = null) {??? closeServer (); ??} ?? if (bytestream! = null) {??? bytestream.close (); ??? Bytestream = null; ??}
?? inetaddress address = inetaddress.getbyName (Host); ?? Client = new socket (address, port == - 1? 80: port); ?? Client.setSotimeout (5000); ?? Sender = new bufferedoutputstream (Client). getOutputStream ()); ?? Receiver = new bufferedInputStream (client.getinputStream ());?}? / * Close contact with the web server * /? protected void closeserver () throws ioException {?? if (client == null) {??? Return; ??} ?? try {??? client.close (); ??? sender.close (); ??? receiver.close (); ??} ?? catch (IOException i) {??? throw i; ??}
?? client = null; ?? sender = NULL; ?? received = null ;?}
? protected string getURLFORMAT (URL TARGET) {?? string spec = "http: //" Target.Gethost (); ?? IF (target.getport ()! = - 1) {??? spec = ":" TARGET.GETPORT (); ??}
?? Return Spec = target.getfile () ;?}
? / * Transfer data to the web server * /? Protected void sendMessage (String Data) throws oews ooException {?? sender.write (Data.GetBytes (), 0, Data.LEngth ()); ?? sender.flush (); ?
? / * Receive data from the web server * /? Protected void receiveMessage () throws ioException = new byte [1024]; ?? int count = 0; ?? int Word = -1; ?? // Analyze the first line ?? While ((word = receiver.read ())! = - 1) {??? if (word == '/ r' || Word == '/ n') {?? ?? Word = received (); ???? if (word == '/ n') word = receiver.read (); ???? Break; ???} ??? if (count == Data.Length) Data = addcapacity (data); ??? Data [count ] = (byte) word; ??} ?? string message = new string (data, 0, count); ?? int mark = message.indexof (32); ?? Serverversion = message.substring (0, mark); ?? While (Mark
?? responsecode = integer.parseint (MARK 1, Mark = 4);
?? responseMessage = message.substring (Mark, Message.Length ()). Trim ();
?? // Answer status code and handler Please add ?? switch (responsecode) {??? case 400: ???????? case 404: ???? New filenotfoundexception (TARGET)); ??? case 503: ???? throw new oException ("server is not available"); ??} ?? if (word == - 1) throw new protocolexception ("information reception Abnormal termination "); ?? Int symbol = -1; ?? count = 0; ?? // parsing meta information ?? 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) Break Parseline; ????? Symbol = 32 Break; ?????} ????? if (count == Data.Length) Data = addcapacity (data); ????? data [count ] = (byte) symbol; ????} ???? words = -1; ???} ??? Message = new string (data, 0, count); ??? mark = message.inde XOF (':'); ??? String Key = NULL; ??? IF (Mark> 0) Key = Message.Substring (0, mark); ??? Mark ; ??? While (Mark ??? String Value = message.substring (Mark, Message.Length ());
??? Header.Put (key, value);
??? count = 0;
??}
?? // get the text data
?? while (Word = receiver.read ())! = - 1) {
?? IF (count == data.length) Data = addcapacity (data);
?? Data [count ] = (byte) Word;
??}
?? IF (count> 0) BYTESTREAM = New ByteArrayInputStream (data, 0, count); ?? Data = null;
?? closeServer ();
?
PUBLIC STRING GETRESPOONSEMESSAGE () {?? returnrate responseMessage ;?}
PUBLIC INT getResponsecode () {?? returncture ;?}
PUBLIC STRING GETSERVERVERVERSON () {?? Return ServerVersion ;?}
PUBLIC INPUTSTREAM GETINPUTSTREAM () {?? return bytestream ;?}
PUBLIC SYNCHRONIZED STRING GETHEADERKEY (INT i) {?? if (i> = header.size ()) {??? Return null; ??} ?? enumeration enum = header.propertyNames (); ?? String key = null ; ?? for (int J = 0; j <= i; j ) {??? key = (string) enum.nexTelement (); ??} ?? return;
? public synchronized string getHeaderValue (INT i) {?? if (i> = header.size ()) Return null; ?? Return Header.getProperty (GetHeaderKey (i)) ;?}
? public synchronized string getHeaderValue (String key) {?? return header.getProperty (key) ;?}
? protected string getBaseheads () {?? string inf = "user-agent: iCewolfhttp / 1.0 / r / naccept: www / source; text / html; image / gif; * / * / r / n";?? Return INF ;?
? private byte [] addcapacity (byte rece ") {?? byte temp [] = new byte [Rece.Length 1024]; ?? System.ArrayCopy (Rece, 0, Temp, 0, Recength);? ? Return Temp;?}
Public static void main (string [] args) {?? / * ?? http p = new http (); ?? p.get ("http://www.google.com/search?q=java book "); ?? Byte [] bgets = new byte [1024]; ?? ByteaRrayInputStream ps = (ByteaRrayInputStream) p.GETINPUTSTREAM (); ?? int offset = 0; ?? While (offset = ps.read (bgets, 0, 1024)))! = -1) {??? system.out.print (new string (bgets, 0, offset); ??} ?? * / ?? String target = "http: // www. Google.com/search?q=java book";??try {??? URL URL = New URL (TARGET); ??? HTTPURLCONNECTION PCONN = (httpurlconnection) URL.OpenConnection (); ???? // httpurlconnection .setFollowRedirects (true); ??? // pconn.setInstanceFollowRedirects (true); ??? pconn.addRequestProperty ( "User-Agent", "IcewolfHttp / 1.0"); ??? pconn.addRequestProperty ( "Accept", " WWW / source; text / html; image / gif; * / * "); ?????? pconn.connect (); ??? system.out.println (" Connect Status: " PConn.getResponsecode () ); ??? // if (httpurlconnection.http_accepted == pConn.getResponsecode ()) ??? // inputstream in = url.openconnection (); ??? INPUTSTREAM IN = PConn.getInputStream (); ??? system .out.println ("get Status: " pconn.getresponsecode ()); ??? bufferedinputstream buff = new bufferedinputstream (in); ??? reader r = new inputStreamReader (buff); ??? INT c = 0;??? While ((C = R.Read ())! = -1) {???? system.out.print ((char) c); ???} ??? buff.close (); ??? in.close () ; ??? PConn.disconnect (); ??} catch (Malformedurlexception MFE) {??? system.err.println (Target "is not a parsable url"); ??} Catch (IOException IoE) {?? ? System.err.println (iee); ??}
?}}