异步httpclient---HttpAsyncClient的使用

这两天研究了一下异步的httpclient ---- httpAsyncClient

原来使用httpclient都是同步的,如果项目中有大量的httpclient的话,可能会造成阻塞,如果使用异步请求的话可以避免这些问题

可以用在调用第三方接口或者不需要知道请求返回结果的场景下

于是写了一个工具类来封装了同步异步httpclient


github地址:https://github.com/a63881763/HttpAsyncClientUtils



1.首先需要在pom中添加需要的jar

[html]  view plain  copy
  1. <properties>  
  2.         <!-- log4j日志包版本号 -->  
  3.         <slf4j.version>1.7.25</slf4j.version>  
  4.         <log4j.version>2.8.2</log4j.version>  
  5.   
  6.     </properties>  
  7.   
  8.     <dependencies>  
  9.         <dependency>  
  10.             <groupId>org.apache.httpcomponents</groupId>  
  11.             <artifactId>httpclient</artifactId>  
  12.             <version>4.5.1</version>  
  13.         </dependency>  
  14.         <dependency>  
  15.             <groupId>org.apache.httpcomponents</groupId>  
  16.             <artifactId>httpcore</artifactId>  
  17.             <version>4.4.6</version>  
  18.         </dependency>  
  19.         <dependency>  
  20.             <groupId>org.apache.httpcomponents</groupId>  
  21.             <artifactId>httpmime</artifactId>  
  22.             <version>4.3.1</version>  
  23.         </dependency>  
  24.         <dependency>  
  25.             <groupId>org.apache.httpcomponents</groupId>  
  26.             <artifactId>httpasyncclient</artifactId>  
  27.             <version>4.1.3</version>  
  28.         </dependency>  
  29.         <dependency>  
  30.             <groupId>commons-lang</groupId>  
  31.             <artifactId>commons-lang</artifactId>  
  32.             <version>2.6</version>  
  33.         </dependency>  
  34.   
  35.   
  36.         <!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->  
  37.         <!--用log4j接管commons-logging-->  
  38.         <!-- log配置:Log4j2 + Slf4j -->  
  39.         <dependency>  
  40.             <groupId>org.apache.logging.log4j</groupId>  
  41.             <artifactId>log4j-api</artifactId>  
  42.             <version>${log4j.version}</version>  
  43.         </dependency>  
  44.         <dependency>  
  45.             <groupId>org.apache.logging.log4j</groupId>  
  46.             <artifactId>log4j-core</artifactId>  
  47.             <version>${log4j.version}</version>  
  48.         </dependency>  
  49.         <dependency> <!-- 桥接:告诉Slf4j使用Log4j2 -->  
  50.             <groupId>org.apache.logging.log4j</groupId>  
  51.             <artifactId>log4j-slf4j-impl</artifactId>  
  52.             <version>${log4j.version}</version>  
  53.         </dependency>  
  54.         <dependency> <!-- 桥接:告诉commons logging使用Log4j2 -->  
  55.             <groupId>org.apache.logging.log4j</groupId>  
  56.             <artifactId>log4j-jcl</artifactId>  
  57.             <version>${log4j.version}</version>  
  58.         </dependency>  
  59.         <dependency>  
  60.             <groupId>org.slf4j</groupId>  
  61.             <artifactId>slf4j-api</artifactId>  
  62.             <version>${slf4j.version}</version>  
  63.         </dependency>  
  64.   
  65.         <dependency>  
  66.             <groupId>com.alibaba</groupId>  
  67.             <artifactId>fastjson</artifactId>  
  68.             <version>1.2.39</version>  
  69.         </dependency>  
  70.     </dependencies>  


2.HttpAsyncClient的连接池类

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

3.httpclient的工厂类


[java]  view plain  copy
  1. /** 
  2.  * 
  3.  * httpclient 工厂类 
  4.  * */  
  5. public class HttpClientFactory {  
  6.   
  7.     private static HttpAsyncClient httpAsyncClient = new HttpAsyncClient();  
  8.   
  9.     private static HttpSyncClient httpSyncClient = new HttpSyncClient();  
  10.   
  11.     private HttpClientFactory() {  
  12.     }  
  13.   
  14.     private static HttpClientFactory httpClientFactory = new HttpClientFactory();  
  15.   
  16.     public static HttpClientFactory getInstance() {  
  17.   
  18.         return httpClientFactory;  
  19.   
  20.     }  
  21.   
  22.     public HttpAsyncClient getHttpAsyncClientPool() {  
  23.         return httpAsyncClient;  
  24.     }  
  25.   
  26.     public HttpSyncClient getHttpSyncClientPool() {  
  27.         return httpSyncClient;  
  28.     }  
  29.   
  30. }  


4.httpclient的util

2017.11.22

发现每次异步连接回调成功后,连接总是延迟很久关,查了不少资料,

发现httpAsyncClient默认是长连接,所以在不需要长连接的时候记得要把

请求头中的connection设成false





[java]  view plain  copy
  1.   
 
[java]  view plain  copy
  1. /** 
  2.  * 
  3.  * http client 业务逻辑处理类 
  4.  * */  
  5. public class HttpClientUtil {  
  6.   
  7.     private static Logger LOG = LoggerFactory  
  8.             .getLogger(HttpClientUtil.class);  
  9.   
  10.     private static String utf8Charset = "utf-8";  
  11.   
  12.   
  13.     /** 
  14.      * 向指定的url发送一次post请求,参数是List<NameValuePair> 
  15.      * @param baseUrl 请求地址 
  16.      * @param list 请求参数,格式是List<NameValuePair> 
  17.      * @return 返回结果,请求失败时返回null 
  18.      * @apiNote http接口处用 @RequestParam接收参数 
  19.      */  
  20.     public static String httpSyncPost(String baseUrl,List<BasicNameValuePair> list) {  
  21.   
  22.         CloseableHttpClient httpClient = HttpClientFactory.getInstance().getHttpSyncClientPool().getHttpClient();  
  23.         HttpPost httpPost = new HttpPost(baseUrl);  
  24.   
  25.         //Parameters  
  26.         LOG.warn("==== Parameters ======" +list);  
  27.         CloseableHttpResponse response  = null;  
  28.         try {  
  29.             httpPost.setEntity(new UrlEncodedFormEntity(list));  
  30.             response = httpClient.execute(httpPost);  
  31.             LOG.warn("========HttpResponseProxy:========"+response.getStatusLine());  
  32.             HttpEntity entity = response.getEntity();  
  33.             String result = null;  
  34.             if(entity != null){  
  35.                 result = EntityUtils.toString(entity, "UTF-8");  
  36.                 LOG.warn("========Response=======" +result);  
  37.             }  
  38.             EntityUtils.consume(entity);  
  39.             return result;  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }finally {  
  43.             if(response != null){  
  44.                 try {  
  45.                     response.close();  
  46.                 } catch (IOException e) {  
  47.                     e.printStackTrace();  
  48.                 }  
  49.             }  
  50.         }  
  51.         return null;  
  52.     }  
  53.   
  54.     /** 
  55.      * 向指定的url发送一次post请求,参数是字符串 
  56.      * @param baseUrl 请求地址 
  57.      * @param postString 请求参数,格式是json.toString() 
  58.      * @return 返回结果,请求失败时返回null 
  59.      * @apiNote http接口处用 @RequestBody接收参数 
  60.      */  
  61.     public static String httpSyncPost(String baseUrl, String postString)  {  
  62.   
  63.         CloseableHttpClient httpClient = HttpClientFactory.getInstance().getHttpSyncClientPool().getHttpClient();  
  64.         HttpPost httpPost = new HttpPost(baseUrl);  
  65.         //parameters  
  66.         LOG.warn("==== Parameters ======" +postString);  
  67.         CloseableHttpResponse response  = null;  
  68.         try {  
  69.             if(postString == null || "".equals(postString)){  
  70.                 throw new Exception("missing post String");  
  71.             }  
  72.   
  73.             StringEntity stringEntity = new StringEntity(postString.toString(), utf8Charset);  
  74.             stringEntity.setContentEncoding("UTF-8");  
  75.             stringEntity.setContentType("application/json");  
  76.             httpPost.setEntity(stringEntity);  
  77.   
  78.             response = httpClient.execute(httpPost);  
  79.             LOG.warn("========HttpResponseProxy:========"+response.getStatusLine());  
  80.             HttpEntity entity = response.getEntity();  
  81.             String result = null;  
  82.             if(entity != null){  
  83.                 result = EntityUtils.toString(entity, "UTF-8");  
  84.                 LOG.warn("========Response=======" +result);  
  85.             }  
  86.             EntityUtils.consume(entity);  
  87.             return result;  
  88.         } catch (Exception e) {  
  89.             e.printStackTrace();  
  90.         }finally {  
  91.             if(response != null){  
  92.                 try {  
  93.                     response.close();  
  94.                 } catch (IOException e) {  
  95.                     e.printStackTrace();  
  96.                 }  
  97.             }  
  98.         }  
  99.         return null;  
  100.     }  
  101.   
  102.   
  103.     /** 
  104.      * 向指定的url发送一次get请求,参数是List<NameValuePair> 
  105.      * @param baseUrl 请求地址 
  106.      * @param list 请求参数,格式是List<NameValuePair> 
  107.      * @return 返回结果,请求失败时返回null 
  108.      * @apiNote http接口处用 @RequestParam接收参数 
  109.      */  
  110.     public static String httpSyncGet(String baseUrl, List<BasicNameValuePair> list)  {  
  111.   
  112.         CloseableHttpClient httpClient = HttpClientFactory.getInstance().getHttpSyncClientPool().getHttpClient();  
  113.         HttpGet httpGet = new HttpGet(baseUrl);  
  114.         //Parameters  
  115.         LOG.warn("==== Parameters ======" +list);  
  116.         CloseableHttpResponse response  = null;  
  117.         try {  
  118.   
  119.             if(list != null){  
  120.                 String getUrl = EntityUtils  
  121.                         .toString(new UrlEncodedFormEntity(list));  
  122.                 httpGet.setURI(new URI(httpGet.getURI().toString()  
  123.                         + "?" + getUrl));  
  124.             }  
  125.             else{  
  126.                 httpGet.setURI(new URI(httpGet.getURI().toString()));  
  127.             }  
  128.   
  129.             response = httpClient.execute(httpGet);  
  130.             LOG.warn("========HttpResponseProxy:========"+response.getStatusLine());  
  131.             HttpEntity entity = response.getEntity();  
  132.             String result = null;  
  133.             if(entity != null){  
  134.                 result = EntityUtils.toString(entity, "UTF-8");  
  135.                 LOG.warn("========Response=======" +result);  
  136.             }  
  137.             EntityUtils.consume(entity);  
  138.             return result;  
  139.         } catch (Exception e) {  
  140.             e.printStackTrace();  
  141.         }finally {  
  142.             if(response != null){  
  143.                 try {  
  144.                     response.close();  
  145.                 } catch (IOException e) {  
  146.                     e.printStackTrace();  
  147.                 }  
  148.             }  
  149.         }  
  150.         return null;  
  151.     }  
  152.   
  153.     /** 
  154.      * 向指定的url发送一次get请求,参数是字符串 
  155.      * @param baseUrl 请求地址 
  156.      * @param urlParams 请求参数,格式是String 
  157.      * @return 返回结果,请求失败时返回null 
  158.      * @apiNote http接口处用 @RequestParam接收参数 
  159.      */  
  160.     public static String httpSyncGet(String baseUrl,String urlParams)  {  
  161.   
  162.         CloseableHttpClient httpClient = HttpClientFactory.getInstance().getHttpSyncClientPool().getHttpClient();  
  163.         HttpGet httpGet = new HttpGet(baseUrl);  
  164.         //Parameters  
  165.         LOG.warn("==== Parameters ======" +urlParams);  
  166.         CloseableHttpResponse response  = null;  
  167.         try {  
  168.   
  169.             if (null != urlParams || "".equals(urlParams)) {  
  170.   
  171.                 httpGet.setURI(new URI(httpGet.getURI().toString()  
  172.                         + "?" + urlParams));  
  173.             }  
  174.             else{  
  175.                 httpGet.setURI(new URI(httpGet.getURI().toString()));  
  176.             }  
  177.   
  178.             response = httpClient.execute(httpGet);  
  179.             LOG.warn("========HttpResponseProxy:========"+response.getStatusLine());  
  180.             HttpEntity entity = response.getEntity();  
  181.             String result = null;  
  182.             if(entity != null){  
  183.                 result = EntityUtils.toString(entity, "UTF-8");  
  184.                 LOG.warn("========Response=======" +result);  
  185.             }  
  186.             EntityUtils.consume(entity);  
  187.             return result;  
  188.         } catch (Exception e) {  
  189.             e.printStackTrace();  
  190.         }finally {  
  191.             if(response != null){  
  192.                 try {  
  193.                     response.close();  
  194.                 } catch (IOException e) {  
  195.                     e.printStackTrace();  
  196.                 }  
  197.             }  
  198.         }  
  199.         return null;  
  200.     }  
  201.   
  202.   
  203.     /** 
  204.      * 向指定的url发送一次get请求,参数是字符串 
  205.      * @param baseUrl 请求地址 
  206.      * @return 返回结果,请求失败时返回null 
  207.      * @apiNote http接口处用 @RequestParam接收参数 
  208.      */  
  209.     public static String httpSyncGet(String baseUrl)  {  
  210.   
  211.         CloseableHttpClient httpClient = HttpClientFactory.getInstance().getHttpSyncClientPool().getHttpClient();  
  212.         HttpGet httpGet = new HttpGet(baseUrl);  
  213.   
  214.         CloseableHttpResponse response  = null;  
  215.         try {  
  216.             httpGet.setURI(new URI(httpGet.getURI().toString()));  
  217.             response = httpClient.execute(httpGet);  
  218.             LOG.warn("========HttpResponseProxy:========"+response.getStatusLine());  
  219.             HttpEntity entity = response.getEntity();  
  220.             String result = null;  
  221.             if(entity != null){  
  222.                 result = EntityUtils.toString(entity, "UTF-8");  
  223.                 LOG.warn("========Response=======" +result);  
  224.             }  
  225.             EntityUtils.consume(entity);  
  226.             return result;  
  227.         } catch (Exception e) {  
  228.             e.printStackTrace();  
  229.         }finally {  
  230.             if(response != null){  
  231.                 try {  
  232.                     response.close();  
  233.                 } catch (IOException e) {  
  234.                     e.printStackTrace();  
  235.                 }  
  236.             }  
  237.         }  
  238.         return null;  
  239.     }  
  240.   
  241.   
  242.   
  243.     /** 
  244.      * 向指定的url发送一次异步post请求,参数是字符串 
  245.      * @param baseUrl 请求地址 
  246.      * @param postString 请求参数,格式是json.toString() 
  247.      * @param urlParams 请求参数,格式是String 
  248.      * @param callback 回调方法,格式是FutureCallback 
  249.      * @return 返回结果,请求失败时返回null 
  250.      * @apiNote http接口处用 @RequestParam接收参数 
  251.      */  
  252.     public static void httpAsyncPost(String baseUrl,String postString,  
  253.                               String urlParams,FutureCallback callback) throws Exception {  
  254.         if (baseUrl == null || "".equals(baseUrl)) {  
  255.             LOG.warn("we don't have base url, check config");  
  256.             throw new Exception("missing base url");  
  257.         }  
  258.         CloseableHttpAsyncClient hc = HttpClientFactory.getInstance().getHttpAsyncClientPool()  
  259.                 .getAsyncHttpClient();  
  260.         try {  
  261.             hc.start();  
  262.             HttpPost httpPost = new HttpPost(baseUrl);  
  263.   
  264.             httpPost.setHeader("Connection","close");  
  265.   
  266.             if (null != postString) {  
  267.                 LOG.debug("exeAsyncReq post postBody={}", postString);  
  268.                 StringEntity entity = new StringEntity(postString.toString(), utf8Charset);  
  269.                 entity.setContentEncoding("UTF-8");  
  270.                 entity.setContentType("application/json");  
  271.                 httpPost.setEntity(entity);  
  272.             }  
  273.   
  274.             if (null != urlParams) {  
  275.   
  276.                 httpPost.setURI(new URI(httpPost.getURI().toString()  
  277.                         + "?" + urlParams));  
  278.             }  
  279.   
  280.             LOG.warn("exeAsyncReq getparams:" + httpPost.getURI());  
  281.   
  282.             hc.execute(httpPost, callback);  
  283.   
  284.         } catch (Exception e) {  
  285.             e.printStackTrace();  
  286.         }  
  287.     }  
  288.   
  289.   
  290.     /** 
  291.      * 向指定的url发送一次异步post请求,参数是字符串 
  292.      * @param baseUrl 请求地址 
  293.      * @param urlParams 请求参数,格式是List<BasicNameValuePair> 
  294.      * @param callback 回调方法,格式是FutureCallback 
  295.      * @return 返回结果,请求失败时返回null 
  296.      * @apiNote http接口处用 @RequestParam接收参数 
  297.      */  
  298.     public static void httpAsyncPost(String baseUrl, List<BasicNameValuePair> postBody,  
  299.                               List<BasicNameValuePair> urlParams, FutureCallback callback ) throws Exception {  
  300.         if (baseUrl == null || "".equals(baseUrl)) {  
  301.             LOG.warn("we don't have base url, check config");  
  302.             throw new Exception("missing base url");  
  303.         }  
  304.   
  305.         try {  
  306.             CloseableHttpAsyncClient hc = HttpClientFactory.getInstance().getHttpAsyncClientPool()  
  307.                     .getAsyncHttpClient();  
  308.   
  309.             hc.start();  
  310.   
  311.             HttpPost httpPost = new HttpPost(baseUrl);  
  312.   
  313.             httpPost.setHeader("Connection","close");  
  314.   
  315.             if (null != postBody) {  
  316.                 LOG.debug("exeAsyncReq post postBody={}", postBody);  
  317.                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(  
  318.                         postBody, "UTF-8");  
  319.                 httpPost.setEntity(entity);  
  320.             }  
  321.   
  322.             if (null != urlParams) {  
  323.   
  324.                 String getUrl = EntityUtils  
  325.                         .toString(new UrlEncodedFormEntity(urlParams));  
  326.   
  327.                 httpPost.setURI(new URI(httpPost.getURI().toString()  
  328.                         + "?" + getUrl));  
  329.             }  
  330.   
  331.             LOG.warn("exeAsyncReq getparams:" + httpPost.getURI());  
  332.   
  333.   
  334.             hc.execute(httpPost, callback);  
  335.   
  336.         } catch (Exception e) {  
  337.             e.printStackTrace();  
  338.         }  
  339.     }  
  340.   
  341.     /** 
  342.      * 向指定的url发送一次异步get请求,参数是String 
  343.      * @param baseUrl 请求地址 
  344.      * @param urlParams 请求参数,格式是String 
  345.      * @param callback 回调方法,格式是FutureCallback 
  346.      * @return 返回结果,请求失败时返回null 
  347.      * @apiNote http接口处用 @RequestParam接收参数 
  348.      */  
  349.     public static void httpAsyncGet(String baseUrl,String urlParams,FutureCallback callback) throws Exception {  
  350.   
  351.         if (baseUrl == null || "".equals(baseUrl)) {  
  352.             LOG.warn("we don't have base url, check config");  
  353.             throw new Exception("missing base url");  
  354.         }  
  355.         CloseableHttpAsyncClient hc = HttpClientFactory.getInstance().getHttpAsyncClientPool()  
  356.                 .getAsyncHttpClient();  
  357.         try {  
  358.   
  359.   
  360.             hc.start();  
  361.   
  362.             HttpGet httpGet = new HttpGet(baseUrl);  
  363.   
  364.             httpGet.setHeader("Connection","close");  
  365.   
  366.             if (null != urlParams || "".equals(urlParams)) {  
  367.   
  368.                 httpGet.setURI(new URI(httpGet.getURI().toString()  
  369.                         + "?" + urlParams));  
  370.             }  
  371.             else{  
  372.                 httpGet.setURI(new URI(httpGet.getURI().toString()));  
  373.             }  
  374.   
  375.             LOG.warn("exeAsyncReq getparams:" + httpGet.getURI());  
  376.   
  377.   
  378.             hc.execute(httpGet,  callback);  
  379.   
  380.         } catch (Exception e) {  
  381.             e.printStackTrace();  
  382.         }  
  383.   
  384.     }  
  385.   
  386.   
  387.     /** 
  388.      * 向指定的url发送一次异步get请求,参数是List<BasicNameValuePair> 
  389.      * @param baseUrl 请求地址 
  390.      * @param urlParams 请求参数,格式是List<BasicNameValuePair> 
  391.      * @param callback 回调方法,格式是FutureCallback 
  392.      * @return 返回结果,请求失败时返回null 
  393.      * @apiNote http接口处用 @RequestParam接收参数 
  394.      */  
  395.     public static void httpAsyncGet(String baseUrl, List<BasicNameValuePair> urlParams, FutureCallback callback) throws Exception {  
  396.         if (baseUrl == null || "".equals(baseUrl)) {  
  397.             LOG.warn("we don't have base url, check config");  
  398.             throw new Exception("missing base url");  
  399.         }  
  400.   
  401.         try {  
  402.             CloseableHttpAsyncClient hc = HttpClientFactory.getInstance().getHttpAsyncClientPool()  
  403.                     .getAsyncHttpClient();  
  404.   
  405.             hc.start();  
  406.   
  407.             HttpPost httpGet = new HttpPost(baseUrl);  
  408.   
  409.             httpGet.setHeader("Connection","close");  
  410.   
  411.             if (null != urlParams) {  
  412.   
  413.                 String getUrl = EntityUtils  
  414.                         .toString(new UrlEncodedFormEntity(urlParams));  
  415.   
  416.                 httpGet.setURI(new URI(httpGet.getURI().toString()  
  417.                         + "?" + getUrl));  
  418.             }  
  419.   
  420.             LOG.warn("exeAsyncReq getparams:" + httpGet.getURI());  
  421.   
  422.   
  423.             hc.execute(httpGet, callback);  
  424.   
  425.         } catch (Exception e) {  
  426.             e.printStackTrace();  
  427.         }  
  428.     }  
  429.   
  430. }  


 
 






工具类种有8种同步异步的post和get请求,通过不同的参数获得结果



本文章参考了http://blog.csdn.net/angjunqiang/article/details/55259170

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值