zoukankan      html  css  js  c++  java
  • 【转】异步的AsyncHttpClient使用详解

    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. }   

    上述代码中的有些参数,在使用的过程中需要替换。

  • 相关阅读:
    【leetcode】704.BinarySearch
    【leetcode】75.Sort Colors
    MongoChef
    问题 工具的缺陷
    MongoDB
    SpringFox
    npm 包管理工具
    RESTful 设计工具和Web框架
    笔记_JSON
    jsoup: Java HTML Parser
  • 原文地址:https://www.cnblogs.com/exmyth/p/7146053.html
Copyright © 2011-2022 走看看