Custom HttpClient tools and httpclient tools

Source: Internet
Author: User

Custom HttpClient tools and httpclient tools

Public class CustomHttpClient {private static String TAG = "CustomHttpClient"; private static final CommonLog log = LogFactory. createLog (); private static final String CHARSET_UTF8 = HTTP. UTF_8; private static final String CHARSET_GB2312 = "GB2312"; private static HttpClient customerHttpClient; private CustomHttpClient () {}/*** HttpClient post method ** @ param url * @ param nameValuePairs * @ return */public Static String evaluate (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.exe cute (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, NameVal UePair... nameValuePairs) throws Exception {log. d ("getFromWebByHttpClient url =" + url); try {// http address // String httpUrl = // "http: // 192.168.1.110: 8080/httpget. 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 the HttpClient object HttpClient httpclient = getHttpClient (context); // request HttpClient and get httpResponse = httpclient.exe cute (httpRequest); // if the request is successful (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 an httpClient instance ** @ return * @ throws Exception */private static synchronized HttpClient getHttpClient (Context context) {if (null = customerHttpClient) {HttpParams params = new BasicHttpParams (); // set some basic parameters: HttpProtocolParams. setVersion (params, HttpVersion. HTTP_1_1); HttpProtocolParams. setContentCharset (par Ams, 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 "); // timeout setting/* obtain the connection timeout from the connection pool */ConnManagerParams. setTimeout (params, 1000);/* connection timeout */int ConnectionTimeOut = 3000; if (! HttpUtils. isWifiDataEnable (context) {ConnectionTimeOut = 10000;} HttpConnectionParams. setConnectionTimeout (params, ConnectionTimeOut);/* request timeout */HttpConnectionParams. setSoTimeout (params, 4000); // set our HttpClient to Support HTTP and HTTPS SchemeRegistry schReg = new SchemeRegistry (); schReg. register (new Scheme ("http", PlainSocketFactory. getSocketFactory (), 80); schReg. register (new Scheme ("https", SSLSocketFactory. getSocketFactory (), 443); // use the thread-safe Connection Manager to create javasconmgr = new ThreadSafeClientConnManager (params, schReg); customerHttpClient = new DefaultHttpClient (conMgr, params );} return customerHttpClient ;}}

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.