HttpClient封装(向后台请求数据)
- public class AlumniHttpClient {
- public static String SERVER_UNAVAIABLE = "Server not available, please try again later!";
- private static AlumniHttpClient instance;
- private static final String CHARSET = HTTP.UTF_8;
- private static HttpClient customerHttpClient;
- public final static int MAX_TOTAL_CONNECTIONS = 800;
- public final static int WAIT_TIMEOUT = 20000;
- public final static int MAX_ROUTE_CONNECTIONS = 400;
- public final static int SO_TIMEOUT = 20000;
- public static synchronized AlumniHttpClient getInstance() {
- if (instance == null) {
- instance = new AlumniHttpClient();
- }
- return instance;
- }
- public static synchronized HttpClient getHttpClient() {
- if (null == customerHttpClient) {
- SSLSocketFactory sf = null;
- KeyStore trustStore;
- try {
- trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null,null);
- sf =new MySSLSocketFactory(trustStore);
- sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- HttpParams params = new BasicHttpParams();
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params,CHARSET);
- 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);
- ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
- ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
- ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
- HttpConnectionParams.setConnectionTimeout(params, SO_TIMEOUT);
- HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
- SchemeRegistry schReg = new SchemeRegistry();
- schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- schReg.register(new Scheme("https", sf, 443));
- ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
- customerHttpClient = new DefaultHttpClient(conMgr, params);
- }
- return customerHttpClient;
- }
- public String post(String url, List<NameValuePair> formparams) throws Exception {
- HttpPost request = new HttpPost(url);
- try {
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,CHARSET);
- request.setEntity(entity);
- HttpClient client = getHttpClient();
- HttpResponse response = client.execute(request);
- if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
- request.abort();
- throw new RuntimeException(SERVER_UNAVAIABLE);
- }
- HttpEntity resEntity = response.getEntity();
- return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
- // return (resEntity == null) ? null : read(resEntity.getContent());
- } catch (ConnectTimeoutException e) {
- request.abort();
- e.printStackTrace();
- return null;
- } catch (IOException e) {
- request.abort();
- e.printStackTrace();
- return null;
- }catch (Exception e) {
- request.abort();
- e.printStackTrace();
- return null;
- }
- }
- //本地修改图片传送到后台
- public final String postByteStream(final String url,final byte[] data,final String fileName) throws IOException {
- HttpPost request = new HttpPost(url);
- try {
- request.setHeader("Content-type","application/octet-stream");
- request.setHeader("Filename", fileName);
- ByteArrayEntity bae = new ByteArrayEntity(data);
- request.setEntity(bae);
- HttpClient client = getHttpClient();
- HttpResponse response = client.execute(request);
- if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
- request.abort();
- throw new RuntimeException("Request Failed");
- }
- HttpEntity resEntity = response.getEntity();
- return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public String get(String url) throws Exception{
- HttpGet get = new HttpGet(url);
- try {
- HttpClient client = getHttpClient();
- HttpResponse response = client.execute(get);
- if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
- get.abort();
- throw new RuntimeException("Request Failed");
- }
- HttpEntity resEntity = response.getEntity();
- return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
- } catch (ClientProtocolException e) {
- get.abort();
- e.printStackTrace();
- return null;
- } catch (IOException e) {
- get.abort();
- e.printStackTrace();
- return null;
- }
- }
- private static String read(InputStream in) throws Exception{
- // TODO Auto-generated method stub
- String text = null;
- BufferedReader reader = new BufferedReader(new InputStreamReader(in),8192);
- StringBuilder sb = new StringBuilder();
- String line = null;
- try {
- while ((line = reader.readLine()) != null) {
- sb.append(line).append(System.getProperty("line.separator"));
- }
- text = sb.toString();
- } finally {
- try {
- in.close();
- } catch (IOException e) {
- }
- }
- return text;
- }
- }
//MySSLSocketFactory
- public class MySSLSocketFactory extends SSLSocketFactory {
- SSLContext sslContext = SSLContext.getInstance("TLS");
- public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
- super(truststore);
- TrustManager tm = new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- @Override
- public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)throws java.security.cert.CertificateException {
- // TODO Auto-generated method stub
- }
- @Override
- public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)throws java.security.cert.CertificateException {
- // TODO Auto-generated method stub
- }
- };
- sslContext.init(null, new TrustManager[] { tm }, null);
- }
- @Override
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
- return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
- }
- @Override
- public Socket createSocket() throws IOException {
- return sslContext.getSocketFactory().createSocket();
- }
- }
转载于:https://blog.51cto.com/emilyzhou/982411