httpclient4.3 Tool Class

Source: Internet
Author: User

httpclient4.3 Java Tools class.

。。

。 A tool class was developed for the project. The httpclient request operation, which is often used, should suffice.


Tool class: http://download.csdn.net/detail/ruishenh/7421641


Package Com.ruishenh.utils;import Java.io.ioexception;import Java.io.unsupportedencodingexception;import Java.net.urisyntaxexception;import Java.nio.charset.charset;import Java.util.arraylist;import Java.util.HashMap; Import Java.util.list;import Java.util.map;import Org.apache.commons.httpclient.httpstatus;import Org.apache.http.httpentity;import Org.apache.http.httpexception;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.config.requestconfig;import Org.apache.http.client.entity.urlencodedformentity;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.urlencodedutils;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclientbuilder;import Org.apache.http.impl.conn.PoolInghttpclientconnectionmanager;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.protocol.http;import Org.apache.http.util.entityutils;public class HttpClientUtils {/** * connection time-out * * public static final int Connection_timeout_ms = 360000;/** * Read Data time-out time */public static final int so_timeout_ms = 360000;pub Lic static final String content_type_json_charset = "APPLICATION/JSON;CHARSET=GBK";p ublic static final string Content_ Type_xml_charset = "APPLICATION/XML;CHARSET=GBK";/** * httpclient character set used when reading content */public static final String Content_ CHARSET = "GBK";p ublic static final CHARSET utf_8 = Charset.forname ("UTF-8");p ublic static final CHARSET GBK = charset.for Name (content_charset);/** * Simple Get call * * @param URL * @param params * @return * @throws clientprotocolexception * @throws IOException * @throws urisyntaxexception */public static string Simplegetinvoke (string url, map<string, string> par AMS) throws Clientprotocolexception, IOException, urisyntaxexception {return SiMplegetinvoke (URL, params,content_charset);} /** * Simple Get call * * @param URL * @param params * @return * @throws clientprotocolexception * @throws IOException * @throws URISyntaxException */public static string Simplegetinvoke (string url, map<string, string> params,string CharSet) Throws Clientprotocolexception, IOException, urisyntaxexception {HttpClient client = Buildhttpclient (false); HttpGet get = buildhttpget (URL, params); HttpResponse response = Client.execute (get); Assertstatus (response); httpentity entity = response.getentity (), if (entity! = null) {String returnstr = entityutils.tostring (Entity,charset); return RETURNSTR;} return null;} /** * Simple Post call * * @param URL * @param params * @return * @throws urisyntaxexception * @throws clientprotocolexception * @throws ioexception */public static string simplepostinvoke (String URL, map<string, string> params) throws URISyntaxException, Clientprotocolexception, IOException {return Simplepostinvoke (URL, params,content_charset);} /** *Simple Post call * * @param URL * @param params * @return * @throws urisyntaxexception * @throws clientprotocolexception * @throw s IOException */public static string simplepostinvoke (String URL, map<string, string> params,string CharSet) throws URISyntaxException, Clientprotocolexception, IOException {HttpClient client = Buildhttpclient (false); HttpPost Postmethod = buildhttppost (URL, params); HttpResponse response = Client.execute (Postmethod); Assertstatus (response); httpentity entity = response.getentity (), if (entity! = null) {String RETURNSTR = entityutils.tostring (entity, CharSet); re Turn returnstr;} return null;} /** * Create HttpClient * * @param ismultithread * @return */public static HttpClient buildhttpclient (Boolean ismultithread) { Closeablehttpclient client;if (ismultithread) client = Httpclientbuilder.create (). Setconnectionmanager (New Poolinghttpclientconnectionmanager ()). build (); elseclient = Httpclientbuilder.create (). build ();//Set proxy server address and port/ /Client.gethostconfiguration (). SetProxy ("Proxy_host_addr ", proxy_port); return client;} /** * Build HttpPost Object * * @param URL * @param headers * @return * @throws unsupportedencodingexception * @throws Urisyntaxex Ception */public static httppost buildhttppost (String URL, map<string, string> params) throws Unsupportedencodingexception, urisyntaxexception {assert.notnull (URL, "URL cannot be null when building HttpPost"); HttpPost post = new HttpPost (URL); Setcommonhttpmethod (POST);  Httpentity he = null;if (params! = null) {list<namevaluepair> Formparams = new arraylist<namevaluepair> (); for (String Key:params.keySet ()) {Formparams.add (New Basicnamevaluepair (Key, Params.get (key)));} he = new Urlencodedformentity (Formparams, GBK);p ost.setentity (He); In requestcontent.process, the length of the message body is written to itself, without writing itself. Write instead test error//Setcontentlength (post, he); return post;} /** * Build HttpGet Object * * @param URL * @param headers * @return * @throws urisyntaxexception */public static HttpGet Buildhtt Pget (String URL, map<string, string> params) throws URISyntaxException {assert.notnull (URL, "URL cannot be null when building HttpGet"); HttpGet get = new HttpGet (buildgeturl (URL, params)); return get;} /** * Build GETURL str * * @param URL * @param params * @return */private static string buildgeturl (String URL, map<st Ring, string> params) {StringBuffer uristr = new StringBuffer (URL); if (params! = null) {list<namevaluepair> PS = New Arraylist<namevaluepair> (); for (String Key:params.keySet ()) {Ps.add (New Basicnamevaluepair (Key, Params.get (key)));} Uristr.append ("?"); Uristr.append (Urlencodedutils.format (PS, utf_8));} return uristr.tostring ();} /** * Set HttpMethod Universal configuration * * @param httpmethod */public static void Setcommonhttpmethod (Httprequestbase httpmethod) {httpMe Thod.setheader (HTTP. Content_encoding, Content_charset);//setting//Contextcoding//httpmethod.setheader (HTTP. Charset_param, Content_charset);//Httpmethod.setheader (HTTP. Content_Type, Content_type_json_charset);//Httpmethod.setheader (HTTP. Content_Type, Content_type_xml_charset);} /** * Set the length of the message body setting messagebody length * * @param httpmethod * @param he */public static void Setcontentlength (Httprequestbase httpmethod , httpentity He) {if (he = = null) {return;} Httpmethod.setheader (HTTP. Content_len, String.valueof (He.getcontentlength ()));} /** * Build Public requestconfig * * @return */public static requestconfig buildrequestconfig () {//Set request and transfer timeout Requestconfig Reque Stconfig = Requestconfig.custom (). SetSocketTimeout (So_timeout_ms). Setconnecttimeout (Connection_timeout_ms). Build (); return requestconfig;} /** * Strong authentication must be 200 state otherwise reported exception * @param res * @throws httpexception */staticvoid Assertstatus (HttpResponse res) throws Ioexceptio N{assert.notnull (res, "HTTP response object is null"); Assert.notnull (Res.getstatusline (), "HTTP response object status is null"), switch (Res.getstatusline (). Getstatuscode ()) {case Httpstatus.sc_ok://case httpstatus.sc_created://case httpstatus.sc_accepted://case HttpStatus.SC_NON_ Authoritative_information://case httpstatus.sc_no_content://case httpstatus.sc_reset_content://case HttpStatus.SC _partial_content://case httpstatus.sc_multi_status:break;default:throw New IOException ("Server response status exception, failed.");}} Private Httpclientutils () {}public static void main (string[] args) throws Clientprotocolexception, IOException, urisyntaxexception {System.out.println (Simplegetinvoke ("http://www.baidu.com", New Hashmap<string, string> () ));}}


httpclient4.3 Tool Class

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.