Implement HTTP Protocol Client Apply with Socket Class

xiaoxiao2021-03-06  94

Implementing the HTTP Protocol client with the Socket class Apply HTTP client program is integrated in the Java language, you can call through 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 by the Email HTTP protocol ** Dark line ** entity request method is a description of this connection work, the current HTTP protocol has developed to version 1.1, it 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. Sending the above message to the web server, if successful, answering format is as follows: HTTP protocol version number response status code response status code Description Received meta information ** Empty line ** entity The above newspaper sent to the client, and receive success , Close the connection between each other, complete a handshake. The following uses the most common GET method to clear the specific packet application: get http://www.youhost.com http / 1.0 accept: 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 automatically, the server returns the following code: http / 1.1 200 ok date: Tue, 14 Sep 1999 02:19:57 GMT Server: Apache / 1.2.6 Connection: Close Content-Type: Text / HTML ** Dark line ** ... ... HTTP / 1.1 means that this HTTP server is version 1.1, 200 is the server requests the customer The response status code, OK is the interpretation of the reputation status code, which is then the metadet information and document text. (Explanation of related response status codes and meta information, please refer to the INETRNET standard draft: RFC2616).

3. HTTP client program: import java.net *; import java.io. *; import java.util.Properties; import java.util.Enumeration; 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 Properties header = new Properties (); public Http () {} public Http (String url ) {GET (URL);} / * GET method According to the URL, the file, database query results, program operation results, and more * / public void get (url) {Try {checkhttp (url); OpenServer .gethost (), target (); string cmd = "get" getURLFormat "http / 1.0 / r / n" getBaseheads () "/ r / n"; sendMessage (cmd); receiveMessage ();} catch (ProtocolException p) {p.printStackTrace (); return;} catch (UnknownHostException e) {e.printStackTrace (); return;} catch (IOException i) i.printStackTrace (); return;}} / * * Head method only requests meta information of the URL, does not include the URL itself. If you doubt the * file on the server, you check the fastest and more effective with this method. * / public void head (string URL) {try {checkhttp (url); OpenServer (), target.getport (); string cmd = "head" getURLFormat (Target) "http / 1.0 / r / N " getBaseheads () " / r / n "; sendMessage (); ReceiveMessage ();} catch (protocolexception p) {p.PrintStackTrace (); return;} catch (unknownhostException e) {E.PrintStackTrace ( Return;} Catch (ooException i) i.printStackTrace (); return;}} / * * The POST method is to transfer data to the server so that the server makes the corresponding process. For example, web pages are commonly used * Submit form.

* / public void post (string url, string content) {Try {checkhttp (url); OpenServer (), target.getport (); string cmd = "post" getURLFormat "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 (); ReceiveMessage ();} catch (protocolexception p) {p.PrintStackTrace (); return;} catch (unknownhostException e) {e.printStackTrace (); return;} catch (IOException i) i.printStackTrace (); return;}} protected void 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 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, IOException {header.clear (); responseMessage = ""; responseCode = -1; try {if (! Client = null) closeServer (); if (byteStream! = null) {byteStream.close (); byteStream = null;} InetAddress address = InetAddress.getByName (host); client = new Socket (address, port == - 1 80: port); sender = new BufferedOutputStream (client?. getOutputStream ()); receiver = new BufferedInputStream (client.getInputStream ());} catch (UnknownHostException u) {throw u;} catch (IOException i) {throw i;}} / * Close the connection to 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; Receiver = null;} protected string geturlformat (url target) {string spec = "http: //" target.gethost (); if (target.getport ()! = - 1) Spec = ": " Target.get (); return spec = target.getfile ();} / * Transfer data to the web server * / protected void sendMessage (String D ATA) THROWS IOEXCEPTION {Sender.write (Data.GetBytes (), 0, Data.Length ()); sender.flush ();} / * receives data from the web server * / protected void receiveMessage () THROWS IOEXCEPTION {BYTE Data [] = new byte [1024]; int count = 0; int Word = -1; // Analysis 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 (markresponsecode = integer.parseint (Mark 1, Mark = 4);

ResponseMessage = message.substring (Mark, Message.Length ()). Trim ();

/ / Answer status code and handle, please add readers to add

Switch (responsecode) {

Case 400:

Throw New IOException ("Error Request");

Case 404:

Throw new filenotfoundexception (getURLFORMAT (TARGET));

Case 503:

Throw new oException ("Server is not available");

}

IF (word == - 1) Throw new protocolexception ("Information Receive Antuster Termination");

INT Symbol = -1;

Count = 0;

// Analyze the 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;

}

Word = -1;

}

Message = New String (DATA, 0, Count);

Mark = message.indexof (':');

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 body data

While (Word = receiver.read ())! = - 1) {

IF (count == data.length) Data = addcapacity (data); data [count ] = (byte) word;

}

IF (count> 0) bytestream = new byterrayinputstream (data, 0, count);

Data = NULL;

CloseServer ();

}

Public string getResponseMessage () {

Return ResponseMessage;

}

Public int getResponsecode () {

Return Responsecode;

}

Public string getServerversion () {

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 Key;

}

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: myselfhttp / 1.0 / r / n"

Accept: 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, Rece.Length);

Return Temp;

}

}

转载请注明原文地址:https://www.9cbs.com/read-96381.html

New Post(0)