The HTTP client program has been integrated into the Java language and can be called through the urlconnection class. Sorry
Yes, since sun did not publish the source code of the HTTP client program, its implementation details are still a mystery. According to HTTP
Use the java.net. Socket class to implement an HTTP client program.
1. Socket class:
Readers who know about TCP/IP protocol set communication know that inter-protocol communication is completed through socket. In
In the java.net package, the socket class is the specific implementation of the socket. It returns
I/O stream for information exchange between protocols.
2. http protocol
The HTTP protocol, like other protocols in the TCP/IP protocol set, follows the customer/server model. Customer
The format of the information sent from the user to the server is as follows:
------------------------------
Request Method urlhttp Protocol version
Submitted metadata
** Empty rows **
Entity
------------------------------
The request method is a description of this connection. Currently, the HTTP protocol has been developed to Version 1.1, including get,
Head, post, delete, options, trace, and put. Metadata is information about the current request. Connect
Excessive metadata analysis allows you to check whether the object data is complete, whether the receiving process is incorrect, and whether the type is matched. RMB
The introduction of information makes HTTP Communication more secure and reliable. The entity is the specific content of the request.
Send the preceding message to the Web server. If the message is sent successfully, the response format is as follows:
--------------------------------
HTTP Protocol version number response status code Description
Received meta information
** Empty rows **
Entity
--------------------------------
The preceding message is sent to the client and received successfully. The connection is closed and a handshake is completed.
The following describes the specific packet application using the most common get method.
----------------------------------
Gethttp: // www. youhost. comhttp/1.0
Accept: www/source; text/html; image/GIF; image/JPEG ;*/*
User_agent: myagent
** Empty rows **
-----------------------------------
This message requests a default HTML document from the host www.youhost.com. Client HTTP Version
The number is version 1.0. the meta information includes the format of the file that can be received. The user agent uses the carriage return line break between each segment.
End with a blank line. After sending to the server, if the execution process is normal, the server returns the following code:
------------------------------------
HTTP/1.20. OK
Date: Tue, 14sep199902: 19: 57gmt
Server: Apache/1.2.6
Connection: Close
Content-Type: text/html
** Empty rows **
<HTML> ------------------------------------
HTTP/1.1 indicates that the HTTP server is Version 1.1, and 200 indicates the server's response status code to the customer's request. OK
It is an explanation of the response status code, followed by the meta information and text of this document. (Related response status codes and metadata
For information explanation, see the draft Inetrnet standard: rfc2616 ).
3. HTTP client program:
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 );
}
/* Based on the URL, the get method will request files, database query results, program running results, and other content */
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 (unknownhostgatetione ){
E. printstacktrace ();
Return;
} Catch (ioexceptioni)
I. printstacktrace ();
Return;
}
}
/*
* The head method only requests URL meta information, excluding the URL itself. If you suspect that
* If the files are the same, use this method to check whether the files are quick and effective.
*/
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 (unknownhostgatetione ){
E. printstacktrace ();
Return;
} Catch (ioexceptioni)
I. printstacktrace ();
Return;
}
}
/*
* The POST method transmits data to the server for processing. For example
* Submit a table.
*/
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 (unknownhostgatetione ){
E. printstacktrace ();
Return;
} Catch (ioexceptioni)
I. printstacktrace ();
Return;
}
}
Protectedvoidcheckhttp (stringurl) throwsprotocolexception {
Try {
Urltarget = newurl (URL );
If (target = NULL |! Target. getprotocol (). touppercase (). Equals ("HTTP "))
Thrownewprotocolexception ("this is not an HTTP Protocol ");
This.tar get = target;
} Catch (malformedurlexceptionm ){
Thrownewprotocolexception ("protocol format error ");
}
}
/*
* Connect to the web server. If the Web server cannot be found, inetaddress will cause unknownhostexception.
* Exception. If the socket connection fails, an ioexception is thrown.
*/
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 ());
Extends ER = newbufferedinputstream (client. getinputstream ());
} Catch (unknownhostexceptionu ){
Throwu;
} Catch (ioexceptioni ){
Throwi;
}
}
/* Close the connection to the Web server */
Protectedvoidcloseserver () throwsioexception {
If (client = NULL) return;
Try {
Client. Close (); Sender. Close (); cycler. Close ();
} Catch (ioexceptioni ){
Throwi;
}
Client = NULL; Sender = NULL; Consumer ER = NULL;
}
Protectedstringgeturlformat (urltarget ){
Stringspec = "http: //" + target. gethost ();
If (target. getport ()! =-1)
Spec + = ":" + target. getport ();
Returnspec + = target. GetFile ();
}
/* Transfer data to the Web server */
Protectedvoidsendmessage (stringdata) throwsioexception {
Sender. Write (data. getbytes (), 0, Data. Length ());
Sender. Flush ();
}
/* Receive data from the Web server */
Protectedvoidreceivemessage () throwsioexception {
Bytedata [] = newbyte [2, 1024];
Intcount = 0;
Intword =-1;
// Parse the first line
While (WORD = author er. Read ())! =-1 ){
If (WORD = '/R' | WORD ='/N '){
WORD = author er. Read ();
If (WORD = '/N') word = author er. 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 ();
// You can add the response status code and process it.
Switch (responsecode ){
Case400:
Thrownewioexception ("error request ");
Case404:
Thrownewfilenotfoundexception (geturlformat (target ));
Case503:
Thrownewioexception ("server unavailable ");
}
If (WORD =-1) thrownewprotocolexception ("message receiving exception termination ");
Intsymbol =-1;
Count = 0;
// Parse metadata
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 = author er. Read ();
If (symbol = '/R' & WORD ='/N '){
WORD = author er. Read ();
If (WORD = '/R') word = author er. 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;
}
// Obtain the body data
While (WORD = author er. 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;
}