Customizing the HttpClient tool class

Source: Internet
Author: User

public class Customhttpclient {private static String TAG = "Customhttpclient";p rivate static final Commonlog log = Logfact Ory.createlog ();p rivate static final String Charset_utf8 = HTTP. Utf_8;private static final String charset_gb2312 = "GB2312";p rivate static HttpClient customerhttpclient;private Customhttpclient () {}/** * HttpClient Post method * * @param URL * @param namevaluepairs * @return */public static String Post Fromwebbyhttpclient (context context, String Url,namevaluepair ... namevaluepairs) {try {list<namevaluepair> params = new arraylist<namevaluepair> (), if (namevaluepairs! = null) {for (int i = 0; i < namevaluepairs.length; I + +) {Params.add (namevaluepairs[i]);}} Urlencodedformentity urlencoded = new urlencodedformentity (PARAMS,CHARSET_UTF8); HttpPost HttpPost = new HttpPost (URL); httppost.setentity (urlencoded); HttpClient client = gethttpclient (context); HttpResponse response = Client.execute (HttpPost); if (Response.getstatusline (). Getstatuscode ()! = HTTPSTATUS.SC_OK){throw new RuntimeException ("request Failed");} Httpentity resentity = response.getentity (); return (resentity = = null)? Null:EntityUtils.toString (Resentity,charset_utf8);} catch (Unsupportedencodingexception e) {LOG.W (TAG, E.getmessage ()); return null;} catch (Clientprotocolexception e) { LOG.W (TAG, E.getmessage ()); return null;} catch (IOException e) {throw new RuntimeException (Context.getresources (). getString (R.string.httperror), E);}} public static string Getfromwebbyhttpclient (context context, string Url,namevaluepair ... namevaluepairs) throws EXCEPTION{LOG.D ("getfromwebbyhttpclient url =" + URL); try {//HTTP address//String httpurl =//"Http://192.168.1.110:8080/htt Pget.jsp?par=httpclient_android_get ";  StringBuilder sb = new StringBuilder (); sb.append (URL); if (namevaluepairs! = null && namevaluepairs.length > 0) {Sb.append ("?"); for (int i = 0; i < namevaluepairs.length; i++) {if (i > 0) {sb.append ("&");} Sb.append (String.Format ("%s=%s", Namevaluepairs[i].getname (), Namevaluepairs[I].getvalue ()));}} HttpGet Connection object HttpGet HttpRequest = new HttpGet (sb.tostring ());//Get HttpClient object httpclient httpclient = Gethttpclient ( context),//Request HttpClient, obtain httpresponsehttpresponse HttpResponse = Httpclient.execute (HttpRequest);//Request Success if ( Httpresponse.getstatusline (). Getstatuscode ()! = HTTPSTATUS.SC_OK) {throw new RuntimeException (Context.getresources ( ). GetString (R.string.httperror));} Return entityutils.tostring (Httpresponse.getentity ());} catch (ParseException e) {//TODO auto-generated catch Blockthrow new RuntimeException (Context.getresources (). getString (R.string.httperror), e);} catch (IOException e) {//TODO auto-generated catch blocklog.e ("IOException"); E.printstacktrace (); throw new RuntimeException (Context.getresources (). getString (R.string.httperror), e);} }/** * Create HttpClient instance * * @return * @throws Exception */private static synchronized HttpClient gethttpclient (Context cont EXT) {if (null = = customerhttpclient) {httpparams params = new Basichttpparams ();//Set some basic parameters HTTPPRotocolparams.setversion (params, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params, Charset_utf8); Httpprotocolparams.setuseexpectcontinue (params, true); Httpprotocolparams.setuseragent (params, "mozilla/5.0" (Linux; U Android 2.2.1;en-us; Nexus one build.frg83) "+" applewebkit/553.1 (khtml,like Gecko) version/4.0 Mobile safari/533.1 ")//time-out setting//timeout for fetching connections from the connection pool */connmanagerparams.settimeout (params, 1000);/* Connection timeout */int connectiontimeout = 3000;if (! Httputils.iswifidataenable (context)) {connectiontimeout = 10000;} Httpconnectionparams.setconnectiontimeout (params, connectiontimeout);/* Request timed out */httpconnectionparams.setsotimeout ( params, 4000);//Set our httpclient to support HTTP and HTTPS two modes schemeregistry Schreg = new Schemeregistry (); Schreg.register (new Scheme ("http", Plainsocketfactory.getsocketfactory (), Schreg.register)), the new scheme ("https", Sslsocketfactory.getsocketfactory (), 443);//Use thread-safe connection management to create httpclientclientconnectionmanager conmgr = new Threadsafeclientconnmanager (params, schreg); CustoMerhttpclient = new Defaulthttpclient (conmgr, params);} return customerhttpclient;}}

Customizing the HttpClient 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.