自訂HttpClient工具類,httpclient工具類

來源:互聯網
上載者:User

自訂HttpClient工具類,httpclient工具類

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方法 *  * @param url * @param nameValuePairs * @return */public static String PostFromWebByHttpClient(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("請求失敗");}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地址// 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連線物件HttpGet httpRequest = new HttpGet(sb.toString());// 取得HttpClient對象HttpClient httpclient = getHttpClient(context);// 請求HttpClient,取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);// 請求成功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);} }/** * 建立httpClient執行個體 *  * @return * @throws Exception */private static synchronized HttpClient getHttpClient(Context context) {if (null == customerHttpClient) {HttpParams params = new BasicHttpParams();// 設定一些基本參數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");// 逾時設定/* 從串連池中取串連的逾時時間 */ConnManagerParams.setTimeout(params, 1000);/* 連線逾時 */int ConnectionTimeOut = 3000;if (!HttpUtils.isWifiDataEnable(context)) {ConnectionTimeOut = 10000;}HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeOut);/* 請求逾時 */HttpConnectionParams.setSoTimeout(params, 4000);// 設定我們的HttpClient支援HTTP和HTTPS兩種模式SchemeRegistry schReg = new SchemeRegistry();schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));// 使用安全執行緒的串連管理來建立HttpClientClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);customerHttpClient = new DefaultHttpClient(conMgr, params);}return customerHttpClient;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.