Implementation of HTTP Access tool classes based on HttpClient4.5.1

Source: Internet
Author: User

This tool class is based on httpclient4.5.1 implementation, click here to view the official version of the HttpClient4.5.1 manual.

1. Pom.xml-dependent Package settings

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId> httpclient</artifactid>
	<version>4.5.1</version>
</dependency>

2. HttpClient Tool Class

Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.net.URISyntaxException;
Import java.util.ArrayList;

Import Java.util.Map;
Import org.apache.http.HttpEntity;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
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.client.methods.HttpRequestBase;
Import Org.apache.http.client.utils.URIBuilder;
Import org.apache.http.impl.client.CloseableHttpClient;

Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
Import Org.apache.http.message.BasicNameValuePair;

Import Org.apache.http.util.EntityUtils;
	/** * * @author Nan 2015-11/public class Httpclientutil {private static poolinghttpclientconnectionmanager cm; Private static String empty_str = "";

	private static String Utf_8 = "UTF-8";
			private static void Init () {if (cm = = null) {cm = new Poolinghttpclientconnectionmanager (); 
	 Cm.setmaxtotal (50);//The maximum connection number of the entire connection pool Cm.setdefaultmaxperroute (5);//maximum number of connections per route, default value is 2}}/** * get httpclient through connection pool *
		* @return */private static closeablehttpclient gethttpclient () {init ();
	Return Httpclients.custom (). Setconnectionmanager (CM). Build (); /** * * @param URL * @return/public static String httpgetrequest (String url) {httpget httpget = new Ht
		Tpget (URL);
	Return GetResult (HttpGet); public static string httpgetrequest (String URL, map<string, object> params) throws URISyntaxException {Uribui
		Lder UB = new UriBuilder ();

		Ub.setpath (URL);
		arraylist<namevaluepair> pairs = Covertparams2nvps (params);

		Ub.setparameters (pairs);
		HttpGet httpget = new HttpGet (Ub.build ());
	Return GetResult (HttpGet); public static string httpgetrequest (string URL, Map<string, object> headers, map<string, object> params) throws URISyntaxException {UriBuilder UB = new
		UriBuilder ();

		Ub.setpath (URL);
		arraylist<namevaluepair> pairs = Covertparams2nvps (params);

		Ub.setparameters (pairs);
		HttpGet httpget = new HttpGet (Ub.build ()); For (map.entry<string, object> param:headers.entrySet ()) {Httpget.addheader (Param.getkey (), String.valueof (PA
		Ram.getvalue ()));
	Return GetResult (HttpGet);
		public static string httppostrequest (string url) {HttpPost httppost = new HttpPost (URL);
	Return GetResult (HttpPost);  public static string httppostrequest (String URL, map<string, object> params) throws Unsupportedencodingexception
		{HttpPost HttpPost = new HttpPost (URL);
		arraylist<namevaluepair> pairs = Covertparams2nvps (params);
		Httppost.setentity (new urlencodedformentity (pairs, utf_8));
	Return GetResult (HttpPost); public static string httppostrequest (string url, map<string, object> headers, map<string, object> params) throws Unsupportedencodingexception {HttpPost HttpPost = new Httppo

		St (URL); For (map.entry<string, object> param:headers.entrySet ()) {Httppost.addheader (Param.getkey (), string.valueof (p
		Aram.getvalue ()));
		} arraylist<namevaluepair> pairs = Covertparams2nvps (params);

		Httppost.setentity (new urlencodedformentity (pairs, utf_8));
	Return GetResult (HttpPost); private static arraylist<namevaluepair> Covertparams2nvps (map<string, object> params) {Arraylist<nam
		evaluepair> pairs = new arraylist<namevaluepair> (); For (map.entry<string, object> param:params.entrySet ()) {Pairs.add (New Basicnamevaluepair (), Param.getkey
		Ng.valueof (Param.getvalue ()));
	return pairs;
		/** * Processing HTTP request * * @param request * @return/private static String GetResult (Httprequestbase request) {
		Closeablehttpclient httpclient = Httpclients.createdefault (); CloseabLehttpclient httpclient = Gethttpclient ();
			try {closeablehttpresponse response = Httpclient.execute (request);
			Response.getstatusline (). Getstatuscode ();
			httpentity entity = response.getentity (); if (entity!= null) {//Long len = Entity.getcontentlength ();//1 indicates length unknown String result = entityutils.tostring (en
				tity);
				Response.close ();
				Httpclient.close ();
			return result;
		} catch (Clientprotocolexception e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
	Finally {} return empty_str; }

}

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.