Apache HttpClient 4.5 Simple and practical

Source: Internet
Author: User

1 Creating a Maven project

<dependencies><dependency><groupid>org.apache.httpcomponents</groupid><artifactid >httpclient</artifactId><version>4.5.2</version></dependency></dependencies>

2. The test code is as follows

package com.iraid.test;import java.io.bufferedreader;import java.io.ioexception;import  java.io.inputstream;import java.io.inputstreamreader;import java.util.arraylist;import  java.util.list;import org.apache.http.httpentity;import org.apache.http.namevaluepair;import  org.apache.http.client.entity.urlencodedformentity;import  Org.apache.http.client.methods.closeablehttpresponse;import org.apache.http.client.methods.httpget;import  org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.httpclients;import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils;/** * apache httpclient-4.5  simple to use.  * CloseableHttpClient  This thread-safe, with   connection pooling   management  *  @author  wangfeihu *  */public class httpclienttest {   public static&nbsP;void main (String[] args)  throws Exception {         closeablehttpclient httpclient = httpclients.createdefault ();          try {             httpget httpget = new httpget ("Http://127.0.0.1:8080/greet");             CloseableHttpResponse response1 =  Httpclient.execute (HttpGet);            //             try {                 system.out.println (Response1.getStatusLine () );                 httpentity  entity1 = response1.GetEntity ();                 //   Handling Response Content                  Inputstream is = entity1.getcontent ();                 string content = convertstreamtostring (IS);                 system.out.println ( Content);                                 //Close Flow                  entityutils.consume ( Entity1);            } finally {                 response1.close ();             }             httppost httppost = new httppost ("Http://127.0.0.1:8080/login");             List <NameValuePair> params =  New arraylist <namevaluepair> ();             params.add (New basicnamevaluepair ("username",  "Ryan"));             params.add (New basicnamevaluepair ("Password",  "secret"));             httppost.setentity (new  Urlencodedformentity (params));             Closeablehttpresponse response2&nbSp;= httpclient.execute (HttpPost);             try {                 system.out.println (Response2.getstatusline ());                 httpentity entity2 = response2.getentity ();                 // do  something useful with the response body                 // and ensure it is fully  consumed                 Inputstream is = entity2.getcontent ();                 stRing content = convertstreamtostring (IS);                 system.out.println (content);                                  entityutils.consume (Entity2);             } finally {                 response2.close ();             }        } finally {             httpclient.close ();         }    }    public static string  convertstreamtostring (INPUtstream is)  {               Bufferedreader reader = new bufferedreader (New inputstreamreader (IS));               stringbuilder sb = new  stringbuilder ();                      String line = null;               try {                   while  (line =  Reader.readline ())  != null)  {                   sb.append (line +  "\ n");                   }               } catch  (ioexception e)  {                   e.printstacktrace ();               } finally {                   try {                        Is.close ();                   } catch  (ioexception e)  {                      e.printstacktrace ();                   }               }               return sb.tostring ();           }   }


3 Connection Pool Management

/** * with htttp request connection pool */public static void pooling () {Poolinghttpclientconnectionmanager cm = new Poolinghttpclientconnectio Nmanager ();//Increase Max Total connection to 200cm.setmaxtotal ($);//increase default Max connection per route to 20cm . Setdefaultmaxperroute;//Increase Max connections for localhost:80 to 50HttpHost localhost = new Httphost ("Locahost" Cm.setmaxperroute (new Httproute (localhost), 50);//Initialize connection closeablehttpclient httpClient = Httpclients.custom (). Setconnectionmanager (CM). Build ();}


This article is from the "Wandering Footsteps" blog, please make sure to keep this source http://now51jq.blog.51cto.com/3474143/1789982

Apache HttpClient 4.5 Simple and practical

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.