HttpClient封装(向后台请求数据)

 
  
  1. public class AlumniHttpClient { 
  2.     public static String SERVER_UNAVAIABLE = "Server not available, please try again later!"
  3.     private static AlumniHttpClient instance; 
  4.     private static final String CHARSET = HTTP.UTF_8; 
  5.     private static HttpClient customerHttpClient; 
  6.     public final static int MAX_TOTAL_CONNECTIONS = 800;   
  7.     public final static int WAIT_TIMEOUT = 20000;   
  8.     public final static int MAX_ROUTE_CONNECTIONS = 400; 
  9.     public final static int SO_TIMEOUT = 20000; 
  10.  
  11.     public static synchronized AlumniHttpClient getInstance() { 
  12.         if (instance == null) { 
  13.             instance = new AlumniHttpClient(); 
  14.         } 
  15.         return instance; 
  16.     } 
  17.  
  18.     public static synchronized HttpClient getHttpClient() { 
  19.         if (null == customerHttpClient) { 
  20.             SSLSocketFactory sf = null
  21.             KeyStore trustStore; 
  22.             try { 
  23.                 trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
  24.                 trustStore.load(null,null); 
  25.                 sf =new MySSLSocketFactory(trustStore); 
  26.                 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
  27.             } catch (Exception e) { 
  28.                 // TODO Auto-generated catch block 
  29.                 e.printStackTrace(); 
  30.             } 
  31.  
  32.             HttpParams params = new BasicHttpParams(); 
  33.             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
  34.             HttpProtocolParams.setContentCharset(params,CHARSET); 
  35.             HttpProtocolParams.setUseExpectContinue(params, true); 
  36.             HttpProtocolParams 
  37.             .setUserAgent( 
  38.                     params, 
  39.                     "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " 
  40.                     + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1"); 
  41.             ConnManagerParams.setTimeout(params, 1000); 
  42.             ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS); 
  43.             ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); 
  44.             ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS); 
  45.             HttpConnectionParams.setConnectionTimeout(params, SO_TIMEOUT); 
  46.             HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT); 
  47.  
  48.             SchemeRegistry schReg = new SchemeRegistry(); 
  49.             schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
  50.             schReg.register(new Scheme("https", sf, 443)); 
  51.  
  52.             ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); 
  53.             customerHttpClient = new DefaultHttpClient(conMgr, params); 
  54.         } 
  55.         return customerHttpClient; 
  56.     } 
  57.  
  58.     public  String post(String url, List<NameValuePair> formparams) throws Exception { 
  59.         HttpPost request = new HttpPost(url); 
  60.         try { 
  61.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,CHARSET); 
  62.             request.setEntity(entity); 
  63.             HttpClient client = getHttpClient(); 
  64.             HttpResponse response = client.execute(request); 
  65.             if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
  66.                 request.abort(); 
  67.                 throw new RuntimeException(SERVER_UNAVAIABLE); 
  68.             } 
  69.             HttpEntity resEntity =  response.getEntity(); 
  70.             return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET); 
  71.             //          return (resEntity == null) ? null : read(resEntity.getContent()); 
  72.         } catch (ConnectTimeoutException e) { 
  73.             request.abort(); 
  74.             e.printStackTrace(); 
  75.             return null
  76.         } catch (IOException e) { 
  77.             request.abort(); 
  78.             e.printStackTrace(); 
  79.             return null
  80.         }catch (Exception e) { 
  81.             request.abort(); 
  82.             e.printStackTrace(); 
  83.             return null
  84.         } 
  85.     } 
     
  86. //本地修改图片传送到后台
  87.     public final String postByteStream(final String url,final byte[] data,final String fileName) throws IOException { 
  88.         HttpPost request = new HttpPost(url); 
  89.         try { 
  90.             request.setHeader("Content-type","application/octet-stream"); 
  91.             request.setHeader("Filename", fileName); 
  92.             ByteArrayEntity bae = new ByteArrayEntity(data); 
  93.             request.setEntity(bae); 
  94.             HttpClient client = getHttpClient(); 
  95.             HttpResponse response = client.execute(request); 
  96.             if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
  97.                 request.abort(); 
  98.                 throw new RuntimeException("Request Failed"); 
  99.             } 
  100.             HttpEntity resEntity =  response.getEntity(); 
  101.             return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET); 
  102.         } catch (Exception e) { 
  103.             e.printStackTrace(); 
  104.             return null
  105.         } 
  106.     } 
  107.  
  108.     public  String get(String url) throws Exception{ 
  109.         HttpGet get = new HttpGet(url); 
  110.         try { 
  111.             HttpClient client = getHttpClient(); 
  112.             HttpResponse response = client.execute(get); 
  113.             if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
  114.                 get.abort(); 
  115.                 throw new RuntimeException("Request Failed"); 
  116.             } 
  117.             HttpEntity resEntity =  response.getEntity(); 
  118.             return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET); 
  119.         } catch (ClientProtocolException e) { 
  120.             get.abort(); 
  121.             e.printStackTrace(); 
  122.             return null
  123.         } catch (IOException e) { 
  124.             get.abort(); 
  125.             e.printStackTrace(); 
  126.             return null
  127.         } 
  128.     } 
  129.  
  130.     private static  String read(InputStream inthrows Exception{ 
  131.         // TODO Auto-generated method stub 
  132.         String text = null
  133.         BufferedReader reader = new BufferedReader(new InputStreamReader(in),8192); 
  134.         StringBuilder sb = new StringBuilder(); 
  135.         String line = null
  136.         try { 
  137.             while ((line = reader.readLine()) != null) { 
  138.                 sb.append(line).append(System.getProperty("line.separator")); 
  139.             } 
  140.             text = sb.toString(); 
  141.         } finally { 
  142.             try { 
  143.                 in.close(); 
  144.             } catch (IOException e) { 
  145.             } 
  146.         } 
  147.         return text; 
  148.     } 

//MySSLSocketFactory 

 
  
  1. public class MySSLSocketFactory extends SSLSocketFactory { 
  2.     SSLContext sslContext = SSLContext.getInstance("TLS"); 
  3.  
  4.     public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { 
  5.  
  6.         super(truststore); 
  7.  
  8.         TrustManager tm = new X509TrustManager() { 
  9.              
  10.             public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
  11.                 return null
  12.             } 
  13.  
  14.             @Override 
  15.             public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)throws java.security.cert.CertificateException { 
  16.                 // TODO Auto-generated method stub 
  17.             } 
  18.  
  19.             @Override 
  20.             public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)throws java.security.cert.CertificateException { 
  21.                 // TODO Auto-generated method stub 
  22.             } 
  23.  
  24.         }; 
  25.         sslContext.init(nullnew TrustManager[] { tm }, null); 
  26.     } 
  27.  
  28.     @Override 
  29.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { 
  30.         return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); 
  31.     } 
  32.  
  33.     @Override 
  34.     public Socket createSocket() throws IOException { 
  35.         return sslContext.getSocketFactory().createSocket(); 
  36.     } 
  37.