Easy to play with HttpClient package HttpClient tool Class (vi), encapsulating input parameters, simplifying tool classes

Source: Internet
Author: User
Tags httpcontext

In writing this tool class when found too many parameters, so that the method flooding, only a send method has more than 30, so the tool class is optimized, the input parameters are encapsulated in an object, so that the extension of input parameters later, directly modify the class is OK.


Not much to say, first on the code:

/** * Request Configuration Class * * @author Arron * @date February 2, 2016 PM 3:14:32 * @version 1.0 */public class Httpconfig {private Httpconfig () {};/** * Get instance * @return */public static Httpconfig custom () {return new Httpconfig ();} /** * HttpClient Object */private HttpClient client;/** * Closeablehttpasyncclient Object */private closeablehttpasyncclient asynclient;/** * Resource URL */private String url;/** * header information */private header[] headers;/** * Request method */private Httpmethods Me thod=httpmethods.get;/** * Request Method name */private String methodname;/** * For cookie Operation */private HttpContext context;/** * Pass Parameters */ Private map<string, object> map;/** * input and output encoding */private String encoding=charset.defaultcharset (). DisplayName ();/* * * Input encoding */private string inenc;/** * Output Encoding */private string outenc;/** * Output Stream object */private outputstream out;/** * Asynchronous Operation Callback Actuator */private Ihandler handler;/** * HttpClient object */public httpconfig Client (HttpClient client) {this.client = Client;return t his;} /** * Closeablehttpasyncclient Object */public httpconfig asynclient (CLoseablehttpasyncclient asynclient) {this.asynclient = Asynclient;return this;} /** * Resource URL */public httpconfig url (String url) {this.url = Url;return this;} /** * Header information */public httpconfig headers (header[] headers) {this.headers = Headers;return this;} /** * Request Methods */public Httpconfig Method (Httpmethods method) {This.method = Method;return this;} /** * Request Method */public Httpconfig MethodName (String methodName) {this.methodname = Methodname;return this;} /** * Cookie Operation related */public httpconfig context (HttpContext context) {This.context = Context;return this;} /** * Pass Parameters */public httpconfig map (map<string, object> map) {this.map = Map;return this;} /** * Input/Output encoding */public httpconfig encoding (String encoding) {//Set input/Output inenc (encoding); Outenc (encoding); this.encoding = Encoding;return this;} /** * Input Encoding */public httpconfig Inenc (String inenc) {This.inenc = Inenc;return this;} /** * Output Encoding */public httpconfig Outenc (String outenc) {This.outenc = Outenc;return this;} /** * Output Stream object */public httpconfig outPutstream out) {this.out = Out;return this;} /** * Asynchronous Operation callback Executor */public Httpconfig handler (Ihandler handler) {This.handler = Handler;return this;} Public HttpClient Client () {return client;} Public Closeablehttpasyncclient asynclient () {return asynclient;} Public header[] Headers () {return headers;} Public String URL () {return URL;} Public Httpmethods Method () {return method;} Public String MethodName () {return methodName;} Public HttpContext context () {return context;} Public map<string, object> map () {return map;} Public String encoding () {return encoding;} Public String Inenc () {return inenc = = null? Encoding:inenc;} Public String Outenc () {return outenc = = null? Encoding:outenc;} Public OutputStream off () {return out;} Public Ihandler Handler () {return handler;}}
set the construction method to private, and then provide a custom () method to get the new instance, all set methods return Httpconfig, which supports chained calls (creator mode).

The core methods of the tool class are as follows:

/** * Request Resource or service * * @param config * @return * @throws httpprocessexception */public static String send (httpconfig config) t Hrows httpprocessexception {return fmt2string (Execute (config), Config.outenc ());} /** * Request Resource or Service * * @param clientclient Object * @param URL resource address * @param httpmethod Request method * @param parasmap Request parameter * @param headers request Header information * @param encoding encoding * @return return processing result * @throws httpprocessexception */private static HttpResponse execute (httpconfig C Onfig) throws Httpprocessexception {if (config.client () ==null) {//detects if Clientconfig.client is set (Create (Config.url ()));} HttpResponse resp = null;try {//Create request object Httprequestbase requests = Getrequest (Config.url (), Config.method ());// Set Header information Request.setheaders (Config.headers ());//Determine whether the set entity (HttpPost, Httpput, Httppatch support only) is supported if ( HttpEntityEnclosingRequestBase.class.isAssignableFrom (Request.getclass ())) {list<namevaluepair> Nvps = new Arraylist<namevaluepair> ();//detects the presence of a parameter in the URL config.url (Utils.checkhasparas (Config.url (), Nvps, Config.inenc () ));//Filling parameter Httpentity entity = utils.map2list (Nvps, Config.map (), Config.inenc ());//setting parameters into the Request object ((Httpentityenclosingrequestbase) Request). setentity (entity); Logger.info ("Requested address:" +config.url ()); if (Nvps.size () >0) {logger.info ("Request parameter:" + Nvps.tostring ());}} Else{int idx = Config.url (). IndexOf ("?"); Logger.info ("Request Address:" +config.url (). substring (0, (idx>0? Idx:config.url (). Length ())), if (idx>0) {Logger.info (" Request parameters: "+config.url (). substring (idx+1));}} Perform the request operation and get the result (synchronous blocking) resp = (Config.context () ==null)? Config.client (). Execute (Request): Config.client (). Execute ( Request, Config.context ());//Get result entity return resp;} catch (IOException e) {throw new Httpprocessexception (e);}} -----------Wah----li--------cut----line--------------//-----------Hua----li--------cut----line--------------//----------- Hua----li--------cut----line--------------/** * into a String * * @param entity entity * @param encoding code * @return * @throws httpprocessex Ception */public static string fmt2string (HttpResponse resp, string encoding) throws Httpprocessexception {string boDY = ""; "try {if (resp.getentity () = null) {//Convert result entity by specified encoding to string type BODY = Entityutils.tostring (resp.getentity (), encoding ); Logger.debug (body);} Entityutils.consume (Resp.getentity ());} catch (ParseException | IOException e) {throw new Httpprocessexception (e);} Finally{close (RESP);} return body;} /** * Convert to stream * * @param entity entity * @param out output stream * @return * @throws httpprocessexception */public static OutputStream FMT 2Stream (HttpResponse resp, outputstream out) throws Httpprocessexception {try {resp.getentity (). WriteTo (out); Entityutils.consume (Resp.getentity ());} catch (ParseException | IOException e) {throw new Httpprocessexception (e);} Finally{close (RESP);} return out;}

Attach the test code again:

public static void Testone () throws Httpprocessexception{system.out.println ("--------Simple call (default post)--------"); String url = "http://tool.oschina.net/"; Httpconfig config = Httpconfig.custom ();//Simple call to String resp = Httpclientutil.get (Config.url (URL)); SYSTEM.OUT.PRINTLN ("Request result content Length:" + resp.length ()); System.out.println ("\n#################################\n"); SYSTEM.OUT.PRINTLN ("--------Join header Settings--------"); Url= "http://blog.csdn.net/xiaoxian8023";//Set header information header[] Headers=httpheader.custom (). useragent ("mozilla/5.0"). Build ();//execute Request RESP = Httpclientutil.get (Config.headers ( headers)); SYSTEM.OUT.PRINTLN ("Request result content Length:" + resp.length ()); System.out.println ("\n#################################\n"); SYSTEM.OUT.PRINTLN ("--------Proxy settings (Bypass certificate validation)-------"); Url= "https://www.facebook.com/"; HttpClient client= hcb.custom (). Timeout (10000). Proxy ("127.0.0.1", 8087). SSL (). build ();//Use Default (Bypass certificate authentication)//execute Request RESP = Httpclientutil.get (config.client (client)); SYSTEM.OUT.PRINTLN ("Request result content Length:" + resp.length ()); System.out.println ("\n#################################\n ");//system.out.println ("--------proxy settings (self-signed certificate authentication) +header+get mode-------");//url =" Https://sso.tgb.com:8443/cas/login ";//client= hcb.custom (). Timeout (10000). SSL (" D:\\keys\\wsriakey "," Tomcat "). Build ();//headers=httpheader.custom (). KeepAlive ("false"). Connection ("Close"). ContentType (headers.app_form_ urlencoded). Build ();////execution Request//resp = Copyofhttpclientutil.get (Config.method (Httpmethods.get));// SYSTEM.OUT.PRINTLN ("Request result content Length:" + resp.length ()), try {System.out.println ("--------download Test-------"), url= "/http Ss.bdimg.com/static/superman/img/logo/logo_white_fe6da1ec.png "; FileOutputStream out = new FileOutputStream (New File ("D://aaa//000.png")); Httpclientutil.down (Httpconfig.custom (). URL (URL). out); Out.flush (); Out.close (); System.out.println ("--------Download Test + proxy-------"); out = new FileOutputStream ("D://aaa//001.png"); Httpclientutil.down (Httpconfig.custom (). Client (client). URL (URL). out); Out.flush (); Out.close ();} catch (IOException e) {e.printstacktrace ();} System.Out.println ("\n#################################\n");} 

you can see that this invocation is more clear and straightforward. When you add features later, it will be easier to change them. the tool class also provides the function of the output stream, which can be used for downloading files or loading verification code pictures, which is very convenient.


The latest complete code is available on github for download: Https://github.com/Arronlong/httpclientUtil.

Easy to play with HttpClient package HttpClient tool Class (vi), encapsulating input parameters, simplifying tool classes

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.