Http communication overview
HTTP communication has two ways to post and get. The former sends data to the server through the Http message entity, which is highly secure and has no limit on the data transmission size. The latter passes it to the server parameters through the URL query string and is displayed in the browser address bar in plain text. It has poor confidentiality and can transmit up to 2048 characters. Essence However, the GET request is not unprepared -the GET request is mostly used to query (read resources), which is efficient. POST requests are used for high security operations such as registration and login and writing data to the database.
In addition to POST and GET, there are other ways to communicate with http! Please refer to the method of http request
Preparation before coding
Before the encoding is performed, we first create a Servlet, which receives the client parameters (name and age) and responds to the client.
@WebServlet (urlpatterns = {"/demo.do"}) Public Class Demoservlet Extends httpservlet {Prive Static Final Long ServerVersionuid = 1L; Public Void Do GetpservletRequest request, httpservletResponse response) Throws servicetexception, IOEXCEPTION {request.SetCharacterenCoding ("UTF- 8 "); Response.SetContentType (" Text/HTML; Charset = UTF-8 "); String name = requestparameter (" name "); Ge "); Printwriter pw = response. getWriter (); pw.print ("You request the service by get. <br />" + "name =" + name + ", Age =" + Age); pw.flush (); pw.close () ;} Public void dopost (httpservletRequest request, httpservletResponse response) Throws servicetexception, IOEXCEPTION f-8 "); Response.SetContentType (" Text/HTML; Charset = UTF-8 "); String name = request. getparameter ("name"); String Age = Request.getparameter ("Age"); Printwriter PW = Response.getWriter (); Pw.print ("You use post method to request this servlet. me = " + Name +", Age = " + Age); pw.flush (); pw.close ();}}
Use JDK to implement HTTP communication
Use urlconnection to implement GET requests
Examine a java.net.url object;
Get a java.net.URLConnection through the openConnection() method of the URL object;
Obtain the input stream through the GetinPutStream () method of the UrlConnection object;
Read the input stream;
Close resources.
Public void get () Throws Exception {url url = new url ("http://127.0.0.1/http/demo.name=jack&age=10"); = url.openconnection (); // Open the connection BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // Get input stream String line = null; StringBuilder sb = New StringBuilder (); WHILE ((LINE = BR.READLINE )! = Null) {sb.append (line + "/n");} System.out.println (sb.tostring ());}
Use httpurlConnection to implement post request
java.net.HttpURLConnection is a subclass of java.net.URL, providing more operations on http (getXXX and setXXX methods). This class defines a series of HTTP status codes:
Public void post () Throws IOEXception {url url = new url ("http://127.0.0.0.1/http/demo.do"); Lconnection) url.openconnection (); httpurlConnection.setdoinput (true); httpurlConnection.setdooutput (true); // Set the connection that can output httpurlconnection.setRequestMethod ("Post"); // Set the request httpurlConnection.SetRequestproperty ("Charset", "UTF-8"); Printwriter PW = New PrintWriter (New BufferedPutStream (httpurlConnection.GetoutPutstream ())); pw.write ("name = welcome"); // Output data to the connection (equivalent to sending data to the server) pw.write ("& age = 14") ; PW .flush (); pw.close (); bufferedReader Br = new bufferedReader (new inputStreamReamReader (httpurlConnection.getInputStream ()), "UTF-8"); l; L; L; Line = BR.Readline ())! = Null) {// Read data sb.append (line + "/n");} System.out.println (sb.tostring ());}
Use httpclient for http communication
HTTPClient greatly simplifies the implementation of http communication in JDK.
Maven dependence:
<Dependency> <Groupid> ORG.APACHE.HTTPCOMPONENTS </Groupid> <Artifactid> HttpClient </Artifactid> <Version> 4.3.6 </Version> </Dependency>
GET request
Public Void HttpClientget () Throws Exception {// Create the httpClient object httpclient client = httpClients.createDefault (); ) Httpget get = new httpget ("http:// /127.0.0.1/http/demo.do?name=admin&age=40"); // Call the execute method of the HttpClient object to obtain the response HttpResponse response = client.execute(get); // Call HttpResponse The Getentity method of the SE object obtains the response entity HttpEntity httpEntity = response.getEntity(); // Use the EntityUtils tool class to get the response string representation String result = EntityUtils.toString(httpEntity,"utf-8"); Systeme m.out.println (result);}
Post request
public void httppclientPost() throws Exception{ // Create HttpClient object HttpClient client = HttpClients.createDefault(); // Create POST request HttpPost post = new Htt pPost("http://127.0.0.1/http/demo.do"); // Create a list container for storing the basic key value pair (Basic key value pair: parameter name-parameter value) list <basicNameValuePair> Parameters = New ArrayList <() (); Parameters.add ("name" , "Zhang San")); parameters.add(new BasicNameValuePair("age", "25")); // Add message entity post.setEntity(new UrlEncodedFormEntity(parameters, "utf- 8 "))) ; // Get the response and convert it into a string HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toSt raing (httpetity, "UTF-8"); System.out.println (result);}
HttpClient is a sub-project under Apache Jakarta Common to provide efficient, latest, feature-rich client programming toolkits that support HTTP protocol, and it supports the latest versions and suggestions of the HTTP protocol. HTTPClient has been applied to many projects, such as the well -known two other open source projects on Apache Jakarta Cactus and HTMLUNIT both use HTTPClient.