posts - 93,  comments - 2,  trackbacks - 0
          package com.zhihe.xqsh.utils;

          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.UnsupportedEncodingException;
          import java.util.Date;
          import java.util.List;

          import org.apache.http.HttpEntity;
          import org.apache.http.HttpResponse;
          import org.apache.http.HttpStatus;
          import org.apache.http.HttpVersion;
          import org.apache.http.NameValuePair;
          import org.apache.http.client.ClientProtocolException;
          import org.apache.http.client.HttpClient;
          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.conn.ClientConnectionManager;
          import org.apache.http.conn.params.ConnManagerParams;
          import org.apache.http.conn.params.ConnRouteParams;
          import org.apache.http.conn.scheme.PlainSocketFactory;
          import org.apache.http.conn.scheme.Scheme;
          import org.apache.http.conn.scheme.SchemeRegistry;
          import org.apache.http.conn.ssl.SSLSocketFactory;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
          import org.apache.http.impl.cookie.BasicClientCookie;
          import org.apache.http.params.BasicHttpParams;
          import org.apache.http.params.HttpConnectionParams;
          import org.apache.http.params.HttpParams;
          import org.apache.http.params.HttpProtocolParams;
          import org.apache.http.util.EntityUtils;

          import com.zhihe.xqsh.network.ServerErrorException;

          import android.accounts.NetworkErrorException;
          import android.annotation.SuppressLint;
          import android.util.Log;


          public class CustomerHttpClient {
          private static final String TAG = CustomerHttpClient.class.getSimpleName();

          private static DefaultHttpClient customerHttpClient;

          private CustomerHttpClient() {
          }

          public static synchronized HttpClient getHttpClient() {
          if (null == customerHttpClient) {
          HttpParams params = new BasicHttpParams();
          // 設置????基本參數
          HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
          HttpProtocolParams.setContentCharset(params, "UTF-8");
          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, 2000);
          ConnManagerParams.setMaxTotalConnections(params, 800);
          /* 連接超時 */
          HttpConnectionParams.setConnectionTimeout(params, 5000);
          /* 請求超時 */
          HttpConnectionParams.setSoTimeout(params, 10000);

          // 設置我們的HttpClient支持HTTP和HTTPS兩種模式
          SchemeRegistry schReg = new SchemeRegistry();
          schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
          schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

          // 使用線程安全的連接管理來創建HttpClient
          ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
          // ????連接數:ConnManagerParams.setMaxTotalConnections(params, 50);
          customerHttpClient = new DefaultHttpClient(conMgr, params);
          }
          return customerHttpClient;
          }

          /**
          * 以get方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String get(String url, String params) throws ServerErrorException, NetworkErrorException {
          int tryTimes = 0;
          NullPointerException ex;
          do {
          try {
          return tryGet(url, params);
          } catch (NullPointerException e) {
          ex = e;
          tryTimes++;
          }
          } while (tryTimes < 3);
          throw ex;
          }

          /**
          * 以get方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String tryGet(String url, String params) throws ServerErrorException, NetworkErrorException {
          try {
          HttpGet request = new HttpGet(url + params);

          /*if (LotteryApplication.isCmwap()) {
          org.apache.http.HttpHost proxy = new org.apache.http.HttpHost("10.0.0.172", 80, "http");
          HttpParams httpParams = new BasicHttpParams();
          ConnRouteParams.setDefaultProxy(httpParams, proxy);
          request.setParams(httpParams);
          }*/

          HttpClient client = getHttpClient();
          HttpResponse response = client.execute(request);
          if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
          throw new ServerErrorException("????????æ???????????");
          }
          HttpEntity resEntity = response.getEntity();
          String result = (resEntity == null) ? null : EntityUtils.toString(resEntity, "UTF-8");
          return result;
          } catch (UnsupportedEncodingException e) {
          logw(e.getMessage());
          return null;
          } catch (ClientProtocolException e) {
          logw(e.getMessage());
          return null;
          } catch (IOException e) {
          throw new NetworkErrorException("??????????????????????", e);
          }
          }

          private static void logw(String string) {
          if (string != null) {
          Log.w(TAG, string);
          }
          }

          /**
          * 以post方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String post(String url, List<NameValuePair> params) throws ServerErrorException, NetworkErrorException {
          return post(url, params, null);
          }

          /**
          * 以post方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @param soTimeout 響應超時時間,單位毫??
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String post(String url, List<NameValuePair> params, int soTimeout) throws ServerErrorException,
          NetworkErrorException {
          HttpParams httpParams;
          if (soTimeout <= 0) {
          httpParams = null;
          } else {
          httpParams = new BasicHttpParams();
          HttpConnectionParams.setSoTimeout(httpParams, soTimeout);
          }
          return post(url, params, httpParams);
          }

          /**
          * 以post方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @param httpParams http參數
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String post(String url, List<NameValuePair> params, HttpParams httpParams) throws ServerErrorException,
          NetworkErrorException {
          int tryTimes = 0;
          NullPointerException ex;
          do {
          try {
          return tryPost(url, params, httpParams);
          } catch (NullPointerException e) {
          ex = e;
          tryTimes++;
          }
          } while (tryTimes < 3);
          throw ex;
          }

          /**
          * 以post方式提交數據
          * @param url 提交地址
          * @param params 參數
          * @param httpParams http參數
          * @return 響應結果
          * @throws ServerErrorException 請求失敗
          * @throws NetworkErrorException 連接失敗
          */
          public static String tryPost(String url, List<NameValuePair> params, HttpParams httpParams) throws ServerErrorException,
          NetworkErrorException {
          try {
          HttpPost request = new HttpPost(url);
          if (params != null && params.size() > 0) {
          request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
          }

          // if (LotteryApplication.isCmwap()) {
          // org.apache.http.HttpHost proxy = new org.apache.http.HttpHost("10.0.0.172", 80, "http");
          // if (httpParams == null)
          // httpParams = new BasicHttpParams();
          // ConnRouteParams.setDefaultProxy(httpParams, proxy);
          // }

          if (httpParams != null)
          request.setParams(httpParams);
          //Log.v("CS", params.toString());
          HttpClient client = getHttpClient();
          HttpResponse response = client.execute(request);
          if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
          //Log.v("CS", params.toString());
          //Log.v("CS", response.getStatusLine().getStatusCode() + "");
          request.abort(); 
          throw new ServerErrorException("????????æ???????????");
          }
          if (response.getStatusLine ().getStatusCode () != 200) {  
          request.abort();  //?ж?????,?????????????????????
                          return null;  
                      } 
          HttpEntity resEntity = response.getEntity();
          String result = (resEntity == null) ? null : EntityUtils.toString(resEntity, "UTF-8");
          //Log.v("CS", params.toString() + "||||" + result);
          return result;
          } catch (UnsupportedEncodingException e) {
          logw(e.getMessage());
          return null;
          } catch (ClientProtocolException e) {
          logw(e.getMessage());
          return null;
          } catch (IOException e) {
          throw new NetworkErrorException(e.getMessage(), e);
          //throw new NetworkErrorException("連接不成功,請檢查網絡設??, e);
          }
          }

          @SuppressLint("SdCardPath")
          public static String download(String url) throws ServerErrorException, NetworkErrorException {
          try {
          //Log.i("http-download", url);
          HttpPost request = new HttpPost(url);
          HttpClient client = getHttpClient();
          HttpResponse response = client.execute(request);
          if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
          throw new ServerErrorException("????????æ???????????");
          }

          HttpEntity entity = response.getEntity();
          InputStream is = entity.getContent();
          if (is == null)
          throw new ServerErrorException("stream is null ");

          String fileExt = url.substring(url.lastIndexOf(".") + 1, url.length()).toLowerCase();
          String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));

          File tempFile = new File("/sdcard/" + fileName + "." + fileExt);
          if (!tempFile.exists())
          tempFile.createNewFile();
          FileOutputStream fileOutputStream = new FileOutputStream(tempFile);

          byte[] buf = new byte[1024];
          int ch;
          while ((ch = is.read(buf)) != -1) {
          fileOutputStream.write(buf, 0, ch);
          }

          fileOutputStream.flush();
          fileOutputStream.close();
          return tempFile.getAbsolutePath();
          } catch (UnsupportedEncodingException e) {
          logw(e.getMessage());
          return null;
          } catch (ClientProtocolException e) {
          logw(e.getMessage());
          return null;
          } catch (IOException e) {
          throw new NetworkErrorException(e.getMessage(), e);
          }
          }

          /**
          * 清空cookie
          */
          public static void clearCookie() {
          if (customerHttpClient != null)
          customerHttpClient.getCookieStore().clear();
          }

          /**
          * 清除指定cookie
          * @param name cookie名稱
          */
          public static void clearCookie(String name) {
          if (customerHttpClient == null)
          return;

          BasicClientCookie expiredCookie = new BasicClientCookie(name, "null");
          expiredCookie.setExpiryDate(new Date(System.currentTimeMillis() - 1000));
          customerHttpClient.getCookieStore().addCookie(expiredCookie);
          }
          }
          posted on 2015-07-13 22:10 Terry Zou 閱讀(287) 評論(0)  編輯  收藏 所屬分類: Android
          <2015年7月>
          2829301234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

          常用鏈接

          留言簿(2)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          相冊

          收藏夾

          Java

          搜索

          •  

          最新隨筆

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 安多县| 江永县| 红桥区| 广水市| 新邵县| 嘉义市| 湘乡市| 基隆市| 濮阳县| 延边| 宁城县| 邯郸市| 方正县| 嘉荫县| 都昌县| 卢湾区| 永修县| 横峰县| 鄂州市| 肥东县| 邵武市| 和顺县| 娱乐| 永兴县| 泰来县| 永寿县| 汉寿县| 和静县| 平乐县| 黔西| 宜黄县| 拉萨市| 汤原县| 梓潼县| 隆德县| 大宁县| 高平市| 沛县| 云阳县| 南川市| 泸水县|