Objective
HTTPthe agreement may be nowInternetmost important protocols, more and moreJavaThe application needs to go directly throughHTTPprotocol to access network resources. Although inJDKof theJava Netaccess has been provided in the packageHTTPthe basic functionality of the Protocol, but for most applications,JDKThe library itself provides not enough functionality to be rich and flexible. HttpClientis aApache Jakarta Commonto provide efficient, up-to-date, feature-rich Client Programming Toolkit for HTTP protocol support, and it supportsHTTPthe latest version and recommendations of the Agreement. HttpClienthas been applied in many projects.
Java.net.HttpURLConnection
HttpURLConnection is the standard class for Java, and HttpURLConnection inherits from URLConnection, which can be used to send a GET request, POST request to a specified Web site. It provides the following convenient methods on the basis of URLConnection:
int Getresponsecode (): Gets the response code of the server.
string Getresponsemessage (): Gets the response message for the server.
string Getresponsemethod (): Gets the method that sent the request.
void Setrequestmethod (String method): Sets the method by which the request is sent.
In general, HttpURLConnection is fully competent if you just need a simple page submission request from your Web site and get a server response. However, in most cases, Web pages may not be as simple as those pages, which are not accessible through a simple URL, and may require the user to log in and have the appropriate permissions to access the page. In this case, you need to deal with the session, cookie processing, if you intend to use HttpURLConnection to deal with these details, of course, it is possible to achieve, but it is very difficult to deal with.
In order to better handle the request to the Web site, including the processing session, cookies and other details, Apache Open source organization provides a httpclient project, look at its name to know, it is a simple HTTP client (not a browser), Can be used to send HTTP requests to receive HTTP responses. However, the server's response is not cached, JavaScript code embedded in the HTML page cannot be executed, and the content of the page is not parsed or processed. Simply put, HttpClient is an enhanced version of Httpurlconnection,httpurlconnection can do things httpclient all can do; httpurlconnection does not provide some features, HttpClient is also provided, but it is focused on how to send requests, receive responses, and manage HTTP connections.
Org.apache.http.client
Using HttpClient to send requests and receive responses is simple, just a few steps below.
1. Create the HttpClient object.
2. Create a HttpGet object if you need to send a GET request, or create a HttpPost object if you need to send a POST request.
3. If you need to send request parameters, you can call the HttpGet, HttpPost common setparams (Hetpparams params) method to add the request parameters, and for HttpPost objects, you can also call Setentity ( Httpentity entity) method to set the request parameters.
4. Call the Execute (httpurirequest request) of the HttpClient object to send the request, and execute the method to return a HttpResponse.
5. Call HttpResponse's Getallheaders (), Getheaders (String name) and other methods to get the server's response header; call HttpResponse getentity () The Httpentity method gets the object that wraps the server's response content. This object is used by the program to obtain the server's response content.
In addition, Android has successfully integrated httpclient, which means developers can use httpclient directly in Android apps to access submission requests and receive responses.
Extended Knowledge: Understanding Httpcore
Project examples
/**
* Post a packet to the remote URL Server
*
* @param URL
* The server that needs to post
* @param paras
* Parameters in the packet
* @return
* @throws Exception
*/
Public Static String postdata (string URL, string data,
String uploadencoding, String responseencoding) throws Exception {
Requestconfig config = requestconfig. Custom (). build ();
HttpClient client = httpclients. Custom ()
. setdefaultrequestconfig (config). build ();
Httpclientcontext context = Httpclientcontext. Create ();
HttpPost post = new httppost (URL);
if (StringUtils. Isnotblank (data)) {
Post.setentity (new stringentity (data, uploadencoding));
}
Closeablehttpresponse response = (closeablehttpresponse) client
. Execute (post, context);
return Entityutils. toString (Response.getentity (), responseencoding);
}
2.
URLConnection
Java comes with java.net
Public Static String Getfromspecialurl (String str,string param) throws exception{
log. info ("Request core Zy ++++++++++++++++++++++++++++++++++++++++++");
URL url = null;
URLConnection conn = null;
BufferedReader BufferedReader = null;
InputStream InputStream = null;
StringBuffer responsexml = null;
PrintWriter output = null;
String result;
Try {
url = new url (str);
log. info ("url" +url);
conn = (URLConnection) url.openconnection ();
Conn.setdoinput (true);
Conn.setdooutput (true);
Conn.setconnecttimeout (1000);
Output = new printwriter (Conn.getoutputstream ());
Output.print (Param.tostring ());
Output.close ();
Responsexml = new stringbuffer ();
InputStream = Conn.getinputstream ();
BufferedReader = new bufferedreader (new InputStreamReader (
InputStream, "GBK"));
String s;
while ((s = bufferedreader.readline ()) = null) {
Responsexml.append (s);
}
Bufferedreader.close ();
} catch (IOException e) {
E.printstacktrace ();
System. out. println ("System handling Exception! ");
}
result = Responsexml.tostring ();
System. out. println ("received message:" + result);
return result;
}
comparison of the main differences between Java.net.URLConnection and Apache HTTPClient
support basic early digest jdk1.2+ ( not supported now digest authentication), can't even handle returned information
Compare items |
URLConnection |
HTTPClient |
How to submit (Methods) |
HEAD, GET, POST, PUT, DELETE, TRACE, OPTIONS |
HEAD, GET, POST, PUT, DELETE, TRACE, OPTIONS, WEBDav, IPP, and even a variety of custom submission methods |
Response (Response Codes) |
can only get HTTP status code less than The status code , response header information (headers), response content . for a response status code of 4xx or 5xx Get Response will only throw any information that is IOException |
Any response information can be obtained at any time: Response status Code, response header information, response content information, and so on. |
| Proxy and socks |
Support, socks support only 4 |
Support, socks support 4 5 |
| Authentication (Authorization) | TD valign= "Center" width= "189" >
support basic , digest authentication |
Cookies |
Not supported |
Support |
Request output stream (True request output streams) |
Before the request is sent, all data is cached. |
Direct output via socket httpoutputstream |
Response input Stream (True response input streams) |
jdk1.2- Support,1.3+ does not support chunked encoding ( Most push server responses are not supported ) |
Support |
Long connections (Persistent Connections) |
jdk1.2-http/1.0 keep-alive,jdk1.3+ http/1.1 Persistent |
Supports http/1.0 keep-alive and http/1.1 persistent |
Pipelining of Requests |
Not supported |
Support |
Set timeout |
Not supported |
Support |
Handling protocols outside of HTTP |
Support such as:FTP, Gopher, mailto, file system |
Not supported |
Open source |
Whether |
Is |
Handling protocols outside of HTTP |
Support such as:FTP, Gopher, mailto, file system |
Not supported |
the difference between apache.commons.Httpclient.HttpClient and apache.http.client.HttpClient
Commons's HttpClient project is now the end of life and is no longer being developed. It has been replaced by Apache Httpcomponents Project HttpClient and Httpcore, offering better performance and greater flexibility.
Apache.http.client.HttpClient