Java Development Foundation--httpclients and network requests

Source: Internet
Author: User

In Java development, it is often necessary to access network resources, usually using the HTTP protocol to access. The simplest way to access the network is to use the Httpclients package provided by Apache. In this blog, I will implement a GET request and a POST request using Httpclients.

The following is access to the "http://www.baidu.com" Web site using GET requests:

public void Get () {closeablehttpclient httpclient = Httpclients.createdefault ();            try {//create HttpGet.            HttpGet httpget = new HttpGet ("http://www.baidu.com");            SYSTEM.OUT.PRINTLN ("Executing request" + Httpget.geturi ());            Executes a GET request.            Closeablehttpresponse response = Httpclient.execute (HttpGet);                try {//Get response entity httpentity entity = response.getentity ();                Print response Status System.out.println (Response.getstatusline ()); if (Entity! = NULL) {//Print response content System.out.println ("Return content:" + entityutils.tostring (E                ntity));            }} finally {Response.close ();        }} catch (Java.io.IOException e) {e.printstacktrace ();        } catch (ParseException e) {e.printstacktrace (); } finally {//closes the connection and frees the resource try {HTTPCLIent.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }

The returned data is not processed, and if JSON is returned, it needs to be parsed. In the case of HTML, the front page display is required. After executing the above code, the returned result is as shown, indicating that the request was successful:



The following code is also a POST request to the same URL:

    public void post () {//creates the default HttpClient instance.        Closeablehttpclient httpclient = Httpclients.createdefault ();        Create HttpPost, or you can put parameters in the URL httppost httppost = new HttpPost ("http://www.baidu.com");        Create a parameter queue, stored as a key-value pair list<namevaluepair> formparams = new arraylist<namevaluepair> ();        Formparams.add (New Basicnamevaluepair ("Phone", "1"));        Urlencodedformentity uefentity;            try {uefentity = new urlencodedformentity (formparams, "UTF-8");            The POST request can be placed in the body by the following method Httppost.setentity (uefentity);            SYSTEM.OUT.PRINTLN ("Executing request" + Httppost.geturi ());            Closeablehttpresponse response = Httpclient.execute (HttpPost);                try {httpentity entity = response.getentity ();                 if (Entity! = null) {System.out.println ("Response content:" + entityutils.tostring (Entity, "UTF-8"));     }} finally {           Response.close ();        }} catch (Clientprotocolexception e) {e.printstacktrace ();        } catch (Unsupportedencodingexception E1) {e1.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();            } finally {//closes the connection, freeing the resource try {httpclient.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }

The big difference between a POST request and a GET request is that the request parameter is placed in the body instead of directly in the URL. The result of the request return is as follows:



After skilled use of httpclients, if other systems also provide a restful interface, then we can be very convenient to call.


Java Development Foundation--httpclients and network requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.