【轉】非同步的AsyncHttpClient使用詳解

weixin_33860553發表於2017-07-10

http://blog.csdn.net/angjunqiang/article/details/55259170

背景

       前面的一篇文章【同步的HttpClient使用詳解】中,提到了服務端通進行網路請求的方式。也講述了在併發量大的情況下使用HttpClient的連線池來提高效能。此方法雖然很有效果,但是當訪問量極大或網路不好的情況下也會出現某些網路請求慢導致其它請求阻塞的情況,為此本文引入了非同步的HttpClient包,將網路請求變成一個非同步的請求,不影響其它的請求。

非同步httpClient需要的jar包

 

[java] view plain copy
 
 print?
  1. <span style="font-size:14px;"> <!-- httpclient -->  
  2.         <dependency>  
  3.             <groupId>org.apache.httpcomponents</groupId>  
  4.             <artifactId>httpclient</artifactId>  
  5.             <version>4.5.1</version>  
  6.         </dependency>  
  7.           
  8.         <dependency>  
  9.             <groupId>org.apache.httpcomponents</groupId>  
  10.             <artifactId>httpcore</artifactId>  
  11.             <version>4.4.6</version>  
  12.         </dependency>  
  13.           
  14.         <dependency>  
  15.             <groupId>org.apache.httpcomponents</groupId>  
  16.             <artifactId>httpmime</artifactId>  
  17.             <version>4.3.1</version>  
  18.         </dependency>  
  19.   
  20.         <dependency>  
  21.             <groupId>org.apache.httpcomponents</groupId>  
  22.             <artifactId>httpasyncclient</artifactId>  
  23.             <version>4.1.3</version>  
  24.         </dependency></span>  

注意:由於非同步的HttpClient比較新,所以儘量使用該文中的版本jar包,或以上版本

使用方法

為了更好的使用,在這裡簡單的使用了工廠模式。將同步的httpclient與非同步的httpclient通過工廠進行例項化

1、定義非同步的httpclient

 

[java] view plain copy
 
 print?
  1. <span style="font-size:14px;">package com.studyproject.httpclient;  
  2.   
  3. import java.nio.charset.CodingErrorAction;  
  4. import java.security.KeyManagementException;  
  5. import java.security.KeyStoreException;  
  6. import java.security.NoSuchAlgorithmException;  
  7. import java.security.UnrecoverableKeyException;  
  8.   
  9. import javax.net.ssl.SSLContext;  
  10.   
  11. import org.apache.http.Consts;  
  12. import org.apache.http.HttpHost;  
  13. import org.apache.http.auth.AuthSchemeProvider;  
  14. import org.apache.http.auth.AuthScope;  
  15. import org.apache.http.auth.MalformedChallengeException;  
  16. import org.apache.http.auth.UsernamePasswordCredentials;  
  17. import org.apache.http.client.CredentialsProvider;  
  18. import org.apache.http.client.config.AuthSchemes;  
  19. import org.apache.http.client.config.RequestConfig;  
  20. import org.apache.http.config.ConnectionConfig;  
  21. import org.apache.http.config.Lookup;  
  22. import org.apache.http.config.Registry;  
  23. import org.apache.http.config.RegistryBuilder;  
  24. import org.apache.http.conn.ssl.SSLContexts;  
  25. import org.apache.http.impl.auth.BasicSchemeFactory;  
  26. import org.apache.http.impl.auth.DigestSchemeFactory;  
  27. import org.apache.http.impl.auth.KerberosSchemeFactory;  
  28. import org.apache.http.impl.auth.NTLMSchemeFactory;  
  29. import org.apache.http.impl.auth.SPNegoSchemeFactory;  
  30. import org.apache.http.impl.client.BasicCookieStore;  
  31. import org.apache.http.impl.client.BasicCredentialsProvider;  
  32. import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;  
  33. import org.apache.http.impl.nio.client.HttpAsyncClients;  
  34. import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;  
  35. import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;  
  36. import org.apache.http.impl.nio.reactor.IOReactorConfig;  
  37. import org.apache.http.nio.conn.NoopIOSessionStrategy;  
  38. import org.apache.http.nio.conn.SchemeIOSessionStrategy;  
  39. import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;  
  40. import org.apache.http.nio.reactor.ConnectingIOReactor;  
  41. import org.apache.http.nio.reactor.IOReactorException;  
  42.   
  43. /** 
  44.  * 非同步的HTTP請求物件,可設定代理 
  45.  */  
  46. public class HttpAsyncClient {  
  47.   
  48.     private static int socketTimeout = 1000;// 設定等待資料超時時間5秒鐘 根據業務調整  
  49.   
  50.     private static int connectTimeout = 2000;// 連線超時  
  51.   
  52.     private static int poolSize = 3000;// 連線池最大連線數  
  53.   
  54.     private static int maxPerRoute = 1500;// 每個主機的併發最多隻有1500  
  55.   
  56.     // http代理相關引數  
  57.     private String host = "";  
  58.     private int port = 0;  
  59.     private String username = "";  
  60.     private String password = "";  
  61.   
  62.     // 非同步httpclient  
  63.     private CloseableHttpAsyncClient asyncHttpClient;  
  64.   
  65.     // 非同步加代理的httpclient  
  66.     private CloseableHttpAsyncClient proxyAsyncHttpClient;  
  67.   
  68.     public HttpAsyncClient() {  
  69.         try {  
  70.             this.asyncHttpClient = createAsyncClient(false);  
  71.             this.proxyAsyncHttpClient = createAsyncClient(true);  
  72.         } catch (Exception e) {  
  73.             e.printStackTrace();  
  74.         }  
  75.   
  76.     }  
  77.   
  78.     public CloseableHttpAsyncClient createAsyncClient(boolean proxy)  
  79.             throws KeyManagementException, UnrecoverableKeyException,  
  80.             NoSuchAlgorithmException, KeyStoreException,  
  81.             MalformedChallengeException, IOReactorException {  
  82.   
  83.         RequestConfig requestConfig = RequestConfig.custom()  
  84.                 .setConnectTimeout(connectTimeout)  
  85.                 .setSocketTimeout(socketTimeout).build();  
  86.   
  87.         SSLContext sslcontext = SSLContexts.createDefault();  
  88.   
  89.         UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(  
  90.                 username, password);  
  91.   
  92.         CredentialsProvider credentialsProvider = new BasicCredentialsProvider();  
  93.         credentialsProvider.setCredentials(AuthScope.ANY, credentials);  
  94.   
  95.         // 設定協議http和https對應的處理socket連結工廠的物件  
  96.         Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder  
  97.                 .<SchemeIOSessionStrategy> create()  
  98.                 .register("http", NoopIOSessionStrategy.INSTANCE)  
  99.                 .register("https", new SSLIOSessionStrategy(sslcontext))  
  100.                 .build();  
  101.   
  102.         // 配置io執行緒  
  103.         IOReactorConfig ioReactorConfig = IOReactorConfig.custom()  
  104.                 .setIoThreadCount(Runtime.getRuntime().availableProcessors())  
  105.                 .build();  
  106.         // 設定連線池大小  
  107.         ConnectingIOReactor ioReactor;  
  108.         ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);  
  109.         PoolingNHttpClientConnectionManager conMgr = new PoolingNHttpClientConnectionManager(  
  110.                 ioReactor, null, sessionStrategyRegistry, null);  
  111.   
  112.         if (poolSize > 0) {  
  113.             conMgr.setMaxTotal(poolSize);  
  114.         }  
  115.   
  116.         if (maxPerRoute > 0) {  
  117.             conMgr.setDefaultMaxPerRoute(maxPerRoute);  
  118.         } else {  
  119.             conMgr.setDefaultMaxPerRoute(10);  
  120.         }  
  121.   
  122.         ConnectionConfig connectionConfig = ConnectionConfig.custom()  
  123.                 .setMalformedInputAction(CodingErrorAction.IGNORE)  
  124.                 .setUnmappableInputAction(CodingErrorAction.IGNORE)  
  125.                 .setCharset(Consts.UTF_8).build();  
  126.   
  127.         Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder  
  128.                 .<AuthSchemeProvider> create()  
  129.                 .register(AuthSchemes.BASIC, new BasicSchemeFactory())  
  130.                 .register(AuthSchemes.DIGEST, new DigestSchemeFactory())  
  131.                 .register(AuthSchemes.NTLM, new NTLMSchemeFactory())  
  132.                 .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())  
  133.                 .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())  
  134.                 .build();  
  135.         conMgr.setDefaultConnectionConfig(connectionConfig);  
  136.   
  137.         if (proxy) {  
  138.             return HttpAsyncClients.custom().setConnectionManager(conMgr)  
  139.                     .setDefaultCredentialsProvider(credentialsProvider)  
  140.                     .setDefaultAuthSchemeRegistry(authSchemeRegistry)  
  141.                     .setProxy(new HttpHost(host, port))  
  142.                     .setDefaultCookieStore(new BasicCookieStore())  
  143.                     .setDefaultRequestConfig(requestConfig).build();  
  144.         } else {  
  145.             return HttpAsyncClients.custom().setConnectionManager(conMgr)  
  146.                     .setDefaultCredentialsProvider(credentialsProvider)  
  147.                     .setDefaultAuthSchemeRegistry(authSchemeRegistry)  
  148.                     .setDefaultCookieStore(new BasicCookieStore()).build();  
  149.         }  
  150.   
  151.     }  
  152.   
  153.     public CloseableHttpAsyncClient getAsyncHttpClient() {  
  154.         return asyncHttpClient;  
  155.     }  
  156.   
  157.     public CloseableHttpAsyncClient getProxyAsyncHttpClient() {  
  158.         return proxyAsyncHttpClient;  
  159.     }  
  160. }</span>  


2、定義同步的httpclient

 

 

[java] view plain copy
 
 print?
  1. <span style="font-size:14px;">package com.studyproject.httpclient;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URI;  
  6. import java.net.URISyntaxException;  
  7. import java.nio.charset.Charset;  
  8. import java.security.cert.CertificateException;  
  9. import java.security.cert.X509Certificate;  
  10. import java.util.List;  
  11.   
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManager;  
  14. import javax.net.ssl.X509TrustManager;  
  15.   
  16. import org.apache.commons.lang.StringUtils;  
  17. import org.apache.http.HttpEntity;  
  18. import org.apache.http.HttpResponse;  
  19. import org.apache.http.HttpVersion;  
  20. import org.apache.http.auth.AuthScope;  
  21. import org.apache.http.auth.UsernamePasswordCredentials;  
  22. import org.apache.http.client.ClientProtocolException;  
  23. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  24. import org.apache.http.client.methods.HttpGet;  
  25. import org.apache.http.client.methods.HttpPost;  
  26. import org.apache.http.conn.scheme.PlainSocketFactory;  
  27. import org.apache.http.conn.scheme.Scheme;  
  28. import org.apache.http.conn.scheme.SchemeRegistry;  
  29. import org.apache.http.conn.ssl.SSLSocketFactory;  
  30. import org.apache.http.entity.StringEntity;  
  31. import org.apache.http.impl.client.DefaultHttpClient;  
  32. import org.apache.http.impl.conn.PoolingClientConnectionManager;  
  33. import org.apache.http.message.BasicNameValuePair;  
  34. import org.apache.http.params.BasicHttpParams;  
  35. import org.apache.http.params.CoreConnectionPNames;  
  36. import org.apache.http.params.CoreProtocolPNames;  
  37. import org.apache.http.params.HttpParams;  
  38. import org.apache.http.util.EntityUtils;  
  39. import org.slf4j.Logger;  
  40. import org.slf4j.LoggerFactory;  
  41.   
  42. /** 
  43.  * 同步的HTTP請求物件,支援post與get方法以及可設定代理 
  44.  */  
  45. public class HttpSyncClient {  
  46.   
  47.     private Logger logger = LoggerFactory.getLogger(HttpSyncClient.class);  
  48.   
  49.     private static int socketTimeout = 1000;// 設定等待資料超時時間5秒鐘 根據業務調整  
  50.   
  51.     private static int connectTimeout = 2000;// 連線超時  
  52.   
  53.     private static int maxConnNum = 4000;// 連線池最大連線數  
  54.   
  55.     private static int maxPerRoute = 1500;// 每個主機的併發最多隻有1500  
  56.   
  57.     private static PoolingClientConnectionManager cm;  
  58.   
  59.     private static HttpParams httpParams;  
  60.   
  61.     private static final String DEFAULT_ENCODING = Charset.defaultCharset()  
  62.             .name();  
  63.   
  64.     // proxy代理相關配置  
  65.     private String host = "";  
  66.     private int port = 0;  
  67.     private String username = "";  
  68.     private String password = "";  
  69.   
  70.     private DefaultHttpClient httpClient;  
  71.   
  72.     private DefaultHttpClient proxyHttpClient;  
  73.   
  74.     // 應用啟動的時候就應該執行的方法  
  75.     public HttpSyncClient() {  
  76.   
  77.         this.httpClient = createClient(false);  
  78.   
  79.         this.proxyHttpClient = createClient(true);  
  80.     }  
  81.   
  82.     public DefaultHttpClient createClient(boolean proxy) {  
  83.   
  84.         SchemeRegistry sr = new SchemeRegistry();  
  85.         sr.register(new Scheme("http", 80, PlainSocketFactory  
  86.                 .getSocketFactory()));  
  87.         SSLSocketFactory sslFactory;  
  88.         try {  
  89.             SSLContext sslContext = SSLContext.getInstance("SSL");  
  90.             X509TrustManager tm = new X509TrustManager() {  
  91.                 @Override  
  92.                 public void checkClientTrusted(X509Certificate[] chain,  
  93.                         String authType) throws CertificateException {  
  94.                 }  
  95.   
  96.                 @Override  
  97.                 public void checkServerTrusted(X509Certificate[] chain,  
  98.                         String authType) throws CertificateException {  
  99.                 }  
  100.   
  101.                 @Override  
  102.                 public X509Certificate[] getAcceptedIssuers() {  
  103.                     return null;  
  104.                 }  
  105.             };  
  106.             sslContext.init(null, new TrustManager[] { tm },  
  107.                     new java.security.SecureRandom());  
  108.             sslFactory = new SSLSocketFactory(sslContext,  
  109.                     SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  110.             sr.register(new Scheme("https", 443, sslFactory));  
  111.         } catch (Exception e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.         // 初始化連線池  
  115.         cm = new PoolingClientConnectionManager(sr);  
  116.         cm.setMaxTotal(maxConnNum);  
  117.         cm.setDefaultMaxPerRoute(maxPerRoute);  
  118.         httpParams = new BasicHttpParams();  
  119.         httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,  
  120.                 HttpVersion.HTTP_1_1);  
  121.         httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,  
  122.                 connectTimeout);// 請求超時時間  
  123.         httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,  
  124.                 socketTimeout);// 讀取資料超時時間  
  125.         // 如果啟用了NoDelay策略,httpclient和站點之間傳輸資料時將會盡可能及時地將傳送緩衝區中的資料傳送出去、而不考慮網路頻寬的利用率,這個策略適合對實時性要求高的場景  
  126.         httpParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);  
  127.         httpParams.setBooleanParameter(  
  128.                 CoreConnectionPNames.STALE_CONNECTION_CHECK, true);  
  129.   
  130.         DefaultHttpClient httpclient = new DefaultHttpClient(cm, httpParams);  
  131.   
  132.         if (proxy) {  
  133.             httpclient.getCredentialsProvider().setCredentials(  
  134.                     new AuthScope(host, port),  
  135.                     new UsernamePasswordCredentials(username, password));  
  136.         }  
  137.   
  138.         return httpclient;  
  139.   
  140.     }  
  141.   
  142.     public DefaultHttpClient getHttpClient() {  
  143.         return httpClient;  
  144.     }  
  145.   
  146.     public DefaultHttpClient getProxyClient() {  
  147.         return proxyHttpClient;  
  148.     }  
  149.   
  150.     public String httpGet(String url, List<BasicNameValuePair> parameters) {  
  151.   
  152.         DefaultHttpClient client = getHttpClient();// 預設會到池中查詢可用的連線,如果沒有就新建  
  153.         HttpGet getMethod = null;  
  154.         String returnValue = "";  
  155.         try {  
  156.             getMethod = new HttpGet(url);  
  157.   
  158.             if (null != parameters) {  
  159.                 String params = EntityUtils.toString(new UrlEncodedFormEntity(  
  160.                         parameters, DEFAULT_ENCODING));  
  161.                 getMethod.setURI(new URI(getMethod.getURI().toString() + "?"  
  162.                         + params));  
  163.                 logger.debug("httpGet-getUrl:{}", getMethod.getURI());  
  164.             }  
  165.   
  166.             HttpResponse response = client.execute(getMethod);  
  167.             int statusCode = response.getStatusLine().getStatusCode();  
  168.   
  169.             if (statusCode == 200) {  
  170.                 HttpEntity he = response.getEntity();  
  171.                 returnValue = new String(EntityUtils.toByteArray(he),  
  172.                         DEFAULT_ENCODING);  
  173.                 return returnValue;  
  174.             }  
  175.   
  176.         } catch (UnsupportedEncodingException e) {  
  177.             logger.error(Thread.currentThread().getName()  
  178.                     + "httpGet Send Error,Code error:" + e.getMessage());  
  179.         } catch (ClientProtocolException e) {  
  180.             logger.error(Thread.currentThread().getName()  
  181.                     + "httpGet Send Error,Protocol error:" + e.getMessage());  
  182.         } catch (IOException e) {  
  183.             logger.error(Thread.currentThread().getName()  
  184.                     + "httpGet Send Error,IO error:" + e.getMessage());  
  185.         } catch (URISyntaxException e) {  
  186.             logger.error(Thread.currentThread().getName()  
  187.                     + "httpGet Send Error,IO error:" + e.getMessage());  
  188.         } finally {// 釋放連線,將連線放回到連線池  
  189.             getMethod.releaseConnection();  
  190.   
  191.         }  
  192.         return returnValue;  
  193.   
  194.     }  
  195.   
  196.     public String httpPost(String url, List<BasicNameValuePair> parameters,  
  197.             String requestBody) {  
  198.   
  199.         DefaultHttpClient client = getHttpClient();// 預設會到池中查詢可用的連線,如果沒有就新建  
  200.         HttpPost postMethod = null;  
  201.         String returnValue = "";  
  202.         try {  
  203.             postMethod = new HttpPost(url);  
  204.   
  205.             if (null != parameters) {  
  206.                 String params = EntityUtils.toString(new UrlEncodedFormEntity(  
  207.                         parameters, DEFAULT_ENCODING));  
  208.                 postMethod.setURI(new URI(postMethod.getURI().toString() + "?"  
  209.                         + params));  
  210.                 logger.debug("httpPost-getUrl:{}", postMethod.getURI());  
  211.             }  
  212.   
  213.             if (StringUtils.isNotBlank(requestBody)) {  
  214.                 StringEntity se = new StringEntity(requestBody,  
  215.                         DEFAULT_ENCODING);  
  216.                 postMethod.setEntity(se);  
  217.             }  
  218.   
  219.             HttpResponse response = client.execute(postMethod);  
  220.             int statusCode = response.getStatusLine().getStatusCode();  
  221.   
  222.             if (statusCode == 200) {  
  223.                 HttpEntity he = response.getEntity();  
  224.                 returnValue = new String(EntityUtils.toByteArray(he),  
  225.                         DEFAULT_ENCODING);  
  226.                 return returnValue;  
  227.             }  
  228.   
  229.         } catch (UnsupportedEncodingException e) {  
  230.             logger.error(Thread.currentThread().getName()  
  231.                     + "httpPost Send Error,Code error:" + e.getMessage());  
  232.         } catch (ClientProtocolException e) {  
  233.             logger.error(Thread.currentThread().getName()  
  234.                     + "httpPost Send Error,Protocol error:" + e.getMessage());  
  235.         } catch (IOException e) {  
  236.             logger.error(Thread.currentThread().getName()  
  237.                     + "httpPost Send Error,IO error:" + e.getMessage());  
  238.         } catch (URISyntaxException e) {  
  239.             logger.error(Thread.currentThread().getName()  
  240.                     + "httpPost Send Error,IO error:" + e.getMessage());  
  241.         } finally {// 釋放連線,將連線放回到連線池  
  242.             postMethod.releaseConnection();  
  243.             // 釋放池子中的空閒連線  
  244.             // client.getConnectionManager().closeIdleConnections(30L,  
  245.             // TimeUnit.MILLISECONDS);  
  246.         }  
  247.         return returnValue;  
  248.   
  249.     }  
  250. }</span>  


3、定義httpClient工廠類

 

 

[java] view plain copy
 
 print?
  1. <span style="font-size:14px;">package com.studyproject.httpclient;  
  2.   
  3. /** 
  4.  *  
  5.  * httpclient 工廠類 
  6.  * */  
  7. public class HttpClientFactory {  
  8.   
  9.     private static HttpAsyncClient httpAsyncClient = new HttpAsyncClient();  
  10.   
  11.     private static HttpSyncClient httpSyncClient = new HttpSyncClient();  
  12.   
  13.     private HttpClientFactory() {  
  14.     }  
  15.   
  16.     private static HttpClientFactory httpClientFactory = new HttpClientFactory();  
  17.   
  18.     public static HttpClientFactory getInstance() {  
  19.   
  20.         return httpClientFactory;  
  21.   
  22.     }  
  23.   
  24.     public HttpAsyncClient getHttpAsyncClientPool() {  
  25.         return httpAsyncClient;  
  26.     }  
  27.   
  28.     public HttpSyncClient getHttpSyncClientPool() {  
  29.         return httpSyncClient;  
  30.     }  
  31.   
  32. }</span>  


4、定義httpclient業務邏輯處理類,對外的方法可以通過這個類來封裝

 

 

[java] view plain copy
 
 print?
  1. package com.studyproject.httpclient;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.URI;  
  5. import java.util.List;  
  6.   
  7. import org.apache.http.HttpEntity;  
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.ParseException;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpGet;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.client.methods.HttpRequestBase;  
  14. import org.apache.http.client.protocol.HttpClientContext;  
  15. import org.apache.http.concurrent.FutureCallback;  
  16. import org.apache.http.impl.client.BasicCookieStore;  
  17. import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19. import org.apache.http.util.EntityUtils;  
  20. import org.slf4j.Logger;  
  21. import org.slf4j.LoggerFactory;  
  22.   
  23. /** 
  24.  *  
  25.  * http client 業務邏輯處理類 
  26.  * */  
  27. public class HttpClientService {  
  28.   
  29.     private static Logger LOG = LoggerFactory  
  30.             .getLogger(HttpClientService.class);  
  31.   
  32.     protected void exeAsyncReq(String baseUrl, boolean isPost,  
  33.             List<BasicNameValuePair> urlParams,  
  34.             List<BasicNameValuePair> postBody, FutureCallback callback)  
  35.             throws Exception {  
  36.   
  37.         if (baseUrl == null) {  
  38.             LOG.warn("we don't have base url, check config");  
  39.             throw new Exception("missing base url");  
  40.         }  
  41.   
  42.         HttpRequestBase httpMethod;  
  43.         CloseableHttpAsyncClient hc = null;  
  44.   
  45.         try {  
  46.             hc = HttpClientFactory.getInstance().getHttpAsyncClientPool()  
  47.                     .getAsyncHttpClient();  
  48.   
  49.             hc.start();  
  50.   
  51.             HttpClientContext localContext = HttpClientContext.create();  
  52.             BasicCookieStore cookieStore = new BasicCookieStore();  
  53.   
  54.             if (isPost) {  
  55.                 httpMethod = new HttpPost(baseUrl);  
  56.   
  57.                 if (null != postBody) {  
  58.                     LOG.debug("exeAsyncReq post postBody={}", postBody);  
  59.                     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(  
  60.                             postBody, "UTF-8");  
  61.                     ((HttpPost) httpMethod).setEntity(entity);  
  62.                 }  
  63.   
  64.                 if (null != urlParams) {  
  65.   
  66.                     String getUrl = EntityUtils  
  67.                             .toString(new UrlEncodedFormEntity(urlParams));  
  68.   
  69.                     httpMethod.setURI(new URI(httpMethod.getURI().toString()  
  70.                             + "?" + getUrl));  
  71.                 }  
  72.   
  73.             } else {  
  74.   
  75.                 httpMethod = new HttpGet(baseUrl);  
  76.   
  77.                 if (null != urlParams) {  
  78.   
  79.                     String getUrl = EntityUtils  
  80.                             .toString(new UrlEncodedFormEntity(urlParams));  
  81.   
  82.                     httpMethod.setURI(new URI(httpMethod.getURI().toString()  
  83.                             + "?" + getUrl));  
  84.                 }  
  85.             }  
  86.   
  87.             System.out.println("exeAsyncReq getparams:" + httpMethod.getURI());  
  88.   
  89.             localContext.setAttribute(HttpClientContext.COOKIE_STORE,  
  90.                     cookieStore);  
  91.   
  92.             hc.execute(httpMethod, localContext, callback);  
  93.   
  94.         } catch (Exception e) {  
  95.             e.printStackTrace();  
  96.         }  
  97.   
  98.     }  
  99.   
  100.     protected String getHttpContent(HttpResponse response) {  
  101.   
  102.         HttpEntity entity = response.getEntity();  
  103.         String body = null;  
  104.   
  105.         if (entity == null) {  
  106.             return null;  
  107.         }  
  108.   
  109.         try {  
  110.   
  111.             body = EntityUtils.toString(entity, "utf-8");  
  112.   
  113.         } catch (ParseException e) {  
  114.   
  115.             LOG.warn("the response's content inputstream is corrupt", e);  
  116.         } catch (IOException e) {  
  117.   
  118.             LOG.warn("the response's content inputstream is corrupt", e);  
  119.         }  
  120.         return body;  
  121.     }  
  122. }  


5、使用httpclient,這裡只介紹了非同步的用法

 

 

[java] view plain copy
 
 print?
  1. package com.studyproject.httpclient;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.utils.HttpClientUtils;  
  8. import org.apache.http.concurrent.FutureCallback;  
  9. import org.apache.http.message.BasicNameValuePair;  
  10.   
  11. /** 
  12.  * http client 使用 
  13.  * */  
  14. public class HttClientUseDemo extends HttpClientService {  
  15.   
  16.     public static void main(String[] args) {  
  17.   
  18.         new HttClientUseDemo().getConfCall();  
  19.     }  
  20.   
  21.     public void getConfCall() {  
  22.   
  23.         String url = "http://220.181.14.110/xxxxx/xxxxx/searchbyappid.do";  
  24.   
  25.         List<BasicNameValuePair> urlParams = new ArrayList<BasicNameValuePair>();  
  26.         urlParams.add(new BasicNameValuePair("appid", "2"));  
  27.         exeHttpReq(url, false, urlParams, null, new GetConfCall());  
  28.     }  
  29.   
  30.     public void exeHttpReq(String baseUrl, boolean isPost,  
  31.             List<BasicNameValuePair> urlParams,  
  32.             List<BasicNameValuePair> postBody,  
  33.             FutureCallback<HttpResponse> callback) {  
  34.   
  35.         try {  
  36.             System.out.println("enter exeAsyncReq");  
  37.             exeAsyncReq(baseUrl, isPost, urlParams, postBody, callback);  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.   
  42.     }  
  43.   
  44.     /** 
  45.      * 被回撥的物件,給非同步的httpclient使用 
  46.      *  
  47.      * */  
  48.     class GetConfCall implements FutureCallback<HttpResponse> {  
  49.   
  50.         /** 
  51.          * 請求完成後呼叫該函式 
  52.          */  
  53.         @Override  
  54.         public void completed(HttpResponse response) {  
  55.   
  56.             System.out.println(response.getStatusLine().getStatusCode());  
  57.             System.out.println(getHttpContent(response));  
  58.   
  59.             HttpClientUtils.closeQuietly(response);  
  60.   
  61.         }  
  62.   
  63.         /** 
  64.          * 請求取消後呼叫該函式 
  65.          */  
  66.         @Override  
  67.         public void cancelled() {  
  68.   
  69.         }  
  70.   
  71.         /** 
  72.          * 請求失敗後呼叫該函式 
  73.          */  
  74.         @Override  
  75.         public void failed(Exception e) {  
  76.   
  77.         }  
  78.   
  79.     }  
  80. }   

上述程式碼中的有些引數,在使用的過程中需要替換。

相關文章