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

背景

前面的一篇文章【同步的HttpClient使用详解】中,提到了服务端通进行网络请求的方式。也讲述了在并发量大的情况下使用HttpClient的连接池来提高性能。此方法虽然很有效果,但是当访问量极大或网络不好的情况下也会出现某些网络请求慢导致其它请求阻塞的情况,为此本文引入了异步的HttpClient包,将网络请求变成一个异步的请求,不影响其它的请求。

异步httpClient需要的jar包

  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. <dependency>
  8. <groupId>org.apache.httpcomponents</groupId>
  9. <artifactId>httpcore</artifactId>
  10. <version>4.4.6</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.httpcomponents</groupId>
  14. <artifactId>httpmime</artifactId>
  15. <version>4.3.1</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.apache.httpcomponents</groupId>
  19. <artifactId>httpasyncclient</artifactId>
  20. <version>4.1.3</version>
  21. </dependency></span>

注意:由于异步的HttpClient比较新,所以尽量使用该文中的版本jar包,或以上版本

使用方法

为了更好的使用,在这里简单的使用了工厂模式。将同步的httpclient与异步的httpclient通过工厂进行实例化

1、定义异步的httpclient

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

2、定义同步的httpclient

  1. <span style="font-size:14px;">package com.studyproject.httpclient;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.URI;
  5. import java.net.URISyntaxException;
  6. import java.nio.charset.Charset;
  7. import java.security.cert.CertificateException;
  8. import java.security.cert.X509Certificate;
  9. import java.util.List;
  10. import javax.net.ssl.SSLContext;
  11. import javax.net.ssl.TrustManager;
  12. import javax.net.ssl.X509TrustManager;
  13. import org.apache.commons.lang.StringUtils;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.HttpVersion;
  17. import org.apache.http.auth.AuthScope;
  18. import org.apache.http.auth.UsernamePasswordCredentials;
  19. import org.apache.http.client.ClientProtocolException;
  20. import org.apache.http.client.entity.UrlEncodedFormEntity;
  21. import org.apache.http.client.methods.HttpGet;
  22. import org.apache.http.client.methods.HttpPost;
  23. import org.apache.http.conn.scheme.PlainSocketFactory;
  24. import org.apache.http.conn.scheme.Scheme;
  25. import org.apache.http.conn.scheme.SchemeRegistry;
  26. import org.apache.http.conn.ssl.SSLSocketFactory;
  27. import org.apache.http.entity.StringEntity;
  28. import org.apache.http.impl.client.DefaultHttpClient;
  29. import org.apache.http.impl.conn.PoolingClientConnectionManager;
  30. import org.apache.http.message.BasicNameValuePair;
  31. import org.apache.http.params.BasicHttpParams;
  32. import org.apache.http.params.CoreConnectionPNames;
  33. import org.apache.http.params.CoreProtocolPNames;
  34. import org.apache.http.params.HttpParams;
  35. import org.apache.http.util.EntityUtils;
  36. import org.slf4j.Logger;
  37. import org.slf4j.LoggerFactory;
  38. /**
  39. * 同步的HTTP请求对象,支持post与get方法以及可设置代理
  40. */
  41. public class HttpSyncClient {
  42. private Logger logger = LoggerFactory.getLogger(HttpSyncClient.class);
  43. private static int socketTimeout = 1000;// 设置等待数据超时时间5秒钟 根据业务调整
  44. private static int connectTimeout = 2000;// 连接超时
  45. private static int maxConnNum = 4000;// 连接池最大连接数
  46. private static int maxPerRoute = 1500;// 每个主机的并发最多只有1500
  47. private static PoolingClientConnectionManager cm;
  48. private static HttpParams httpParams;
  49. private static final String DEFAULT_ENCODING = Charset.defaultCharset()
  50. .name();
  51. // proxy代理相关配置
  52. private String host = "";
  53. private int port = 0;
  54. private String username = "";
  55. private String password = "";
  56. private DefaultHttpClient httpClient;
  57. private DefaultHttpClient proxyHttpClient;
  58. // 应用启动的时候就应该执行的方法
  59. public HttpSyncClient() {
  60. this.httpClient = createClient(false);
  61. this.proxyHttpClient = createClient(true);
  62. }
  63. public DefaultHttpClient createClient(boolean proxy) {
  64. SchemeRegistry sr = new SchemeRegistry();
  65. sr.register(new Scheme("http", 80, PlainSocketFactory
  66. .getSocketFactory()));
  67. SSLSocketFactory sslFactory;
  68. try {
  69. SSLContext sslContext = SSLContext.getInstance("SSL");
  70. X509TrustManager tm = new X509TrustManager() {
  71. @Override
  72. public void checkClientTrusted(X509Certificate[] chain,
  73. String authType) throws CertificateException {
  74. }
  75. @Override
  76. public void checkServerTrusted(X509Certificate[] chain,
  77. String authType) throws CertificateException {
  78. }
  79. @Override
  80. public X509Certificate[] getAcceptedIssuers() {
  81. return null;
  82. }
  83. };
  84. sslContext.init(null, new TrustManager[] { tm },
  85. new java.security.SecureRandom());
  86. sslFactory = new SSLSocketFactory(sslContext,
  87. SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  88. sr.register(new Scheme("https", 443, sslFactory));
  89. } catch (Exception e) {
  90. e.printStackTrace();
  91. }
  92. // 初始化连接池
  93. cm = new PoolingClientConnectionManager(sr);
  94. cm.setMaxTotal(maxConnNum);
  95. cm.setDefaultMaxPerRoute(maxPerRoute);
  96. httpParams = new BasicHttpParams();
  97. httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
  98. HttpVersion.HTTP_1_1);
  99. httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
  100. connectTimeout);// 请求超时时间
  101. httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
  102. socketTimeout);// 读取数据超时时间
  103. // 如果启用了NoDelay策略,httpclient和站点之间传输数据时将会尽可能及时地将发送缓冲区中的数据发送出去、而不考虑网络带宽的利用率,这个策略适合对实时性要求高的场景
  104. httpParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
  105. httpParams.setBooleanParameter(
  106. CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
  107. DefaultHttpClient httpclient = new DefaultHttpClient(cm, httpParams);
  108. if (proxy) {
  109. httpclient.getCredentialsProvider().setCredentials(
  110. new AuthScope(host, port),
  111. new UsernamePasswordCredentials(username, password));
  112. }
  113. return httpclient;
  114. }
  115. public DefaultHttpClient getHttpClient() {
  116. return httpClient;
  117. }
  118. public DefaultHttpClient getProxyClient() {
  119. return proxyHttpClient;
  120. }
  121. public String httpGet(String url, List<BasicNameValuePair> parameters) {
  122. DefaultHttpClient client = getHttpClient();// 默认会到池中查询可用的连接,如果没有就新建
  123. HttpGet getMethod = null;
  124. String returnValue = "";
  125. try {
  126. getMethod = new HttpGet(url);
  127. if (null != parameters) {
  128. String params = EntityUtils.toString(new UrlEncodedFormEntity(
  129. parameters, DEFAULT_ENCODING));
  130. getMethod.setURI(new URI(getMethod.getURI().toString() + "?"
  131. + params));
  132. logger.debug("httpGet-getUrl:{}", getMethod.getURI());
  133. }
  134. HttpResponse response = client.execute(getMethod);
  135. int statusCode = response.getStatusLine().getStatusCode();
  136. if (statusCode == 200) {
  137. HttpEntity he = response.getEntity();
  138. returnValue = new String(EntityUtils.toByteArray(he),
  139. DEFAULT_ENCODING);
  140. return returnValue;
  141. }
  142. } catch (UnsupportedEncodingException e) {
  143. logger.error(Thread.currentThread().getName()
  144. + "httpGet Send Error,Code error:" + e.getMessage());
  145. } catch (ClientProtocolException e) {
  146. logger.error(Thread.currentThread().getName()
  147. + "httpGet Send Error,Protocol error:" + e.getMessage());
  148. } catch (IOException e) {
  149. logger.error(Thread.currentThread().getName()
  150. + "httpGet Send Error,IO error:" + e.getMessage());
  151. } catch (URISyntaxException e) {
  152. logger.error(Thread.currentThread().getName()
  153. + "httpGet Send Error,IO error:" + e.getMessage());
  154. } finally {// 释放连接,将连接放回到连接池
  155. getMethod.releaseConnection();
  156. }
  157. return returnValue;
  158. }
  159. public String httpPost(String url, List<BasicNameValuePair> parameters,
  160. String requestBody) {
  161. DefaultHttpClient client = getHttpClient();// 默认会到池中查询可用的连接,如果没有就新建
  162. HttpPost postMethod = null;
  163. String returnValue = "";
  164. try {
  165. postMethod = new HttpPost(url);
  166. if (null != parameters) {
  167. String params = EntityUtils.toString(new UrlEncodedFormEntity(
  168. parameters, DEFAULT_ENCODING));
  169. postMethod.setURI(new URI(postMethod.getURI().toString() + "?"
  170. + params));
  171. logger.debug("httpPost-getUrl:{}", postMethod.getURI());
  172. }
  173. if (StringUtils.isNotBlank(requestBody)) {
  174. StringEntity se = new StringEntity(requestBody,
  175. DEFAULT_ENCODING);
  176. postMethod.setEntity(se);
  177. }
  178. HttpResponse response = client.execute(postMethod);
  179. int statusCode = response.getStatusLine().getStatusCode();
  180. if (statusCode == 200) {
  181. HttpEntity he = response.getEntity();
  182. returnValue = new String(EntityUtils.toByteArray(he),
  183. DEFAULT_ENCODING);
  184. return returnValue;
  185. }
  186. } catch (UnsupportedEncodingException e) {
  187. logger.error(Thread.currentThread().getName()
  188. + "httpPost Send Error,Code error:" + e.getMessage());
  189. } catch (ClientProtocolException e) {
  190. logger.error(Thread.currentThread().getName()
  191. + "httpPost Send Error,Protocol error:" + e.getMessage());
  192. } catch (IOException e) {
  193. logger.error(Thread.currentThread().getName()
  194. + "httpPost Send Error,IO error:" + e.getMessage());
  195. } catch (URISyntaxException e) {
  196. logger.error(Thread.currentThread().getName()
  197. + "httpPost Send Error,IO error:" + e.getMessage());
  198. } finally {// 释放连接,将连接放回到连接池
  199. postMethod.releaseConnection();
  200. // 释放池子中的空闲连接
  201. // client.getConnectionManager().closeIdleConnections(30L,
  202. // TimeUnit.MILLISECONDS);
  203. }
  204. return returnValue;
  205. }
  206. }</span>

3、定义httpClient工厂类

  1. <span style="font-size:14px;">package com.studyproject.httpclient;
  2. /**
  3. *
  4. * httpclient 工厂类
  5. * */
  6. public class HttpClientFactory {
  7. private static HttpAsyncClient httpAsyncClient = new HttpAsyncClient();
  8. private static HttpSyncClient httpSyncClient = new HttpSyncClient();
  9. private HttpClientFactory() {
  10. }
  11. private static HttpClientFactory httpClientFactory = new HttpClientFactory();
  12. public static HttpClientFactory getInstance() {
  13. return httpClientFactory;
  14. }
  15. public HttpAsyncClient getHttpAsyncClientPool() {
  16. return httpAsyncClient;
  17. }
  18. public HttpSyncClient getHttpSyncClientPool() {
  19. return httpSyncClient;
  20. }
  21. }</span>

4、定义httpclient业务逻辑处理类,对外的方法可以通过这个类来封装

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

5、使用httpclient,这里只介绍了异步的用法

  1. package com.studyproject.httpclient;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.client.utils.HttpClientUtils;
  6. import org.apache.http.concurrent.FutureCallback;
  7. import org.apache.http.message.BasicNameValuePair;
  8. /**
  9. * http client 使用
  10. * */
  11. public class HttClientUseDemo extends HttpClientService {
  12. public static void main(String[] args) {
  13. new HttClientUseDemo().getConfCall();
  14. }
  15. public void getConfCall() {
  16. String url = "http://220.181.14.110/xxxxx/xxxxx/searchbyappid.do";
  17. List<BasicNameValuePair> urlParams = new ArrayList<BasicNameValuePair>();
  18. urlParams.add(new BasicNameValuePair("appid", "2"));
  19. exeHttpReq(url, false, urlParams, null, new GetConfCall());
  20. }
  21. public void exeHttpReq(String baseUrl, boolean isPost,
  22. List<BasicNameValuePair> urlParams,
  23. List<BasicNameValuePair> postBody,
  24. FutureCallback<HttpResponse> callback) {
  25. try {
  26. System.out.println("enter exeAsyncReq");
  27. exeAsyncReq(baseUrl, isPost, urlParams, postBody, callback);
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. /**
  33. * 被回调的对象,给异步的httpclient使用
  34. *
  35. * */
  36. class GetConfCall implements FutureCallback<HttpResponse> {
  37. /**
  38. * 请求完成后调用该函数
  39. */
  40. @Override
  41. public void completed(HttpResponse response) {
  42. System.out.println(response.getStatusLine().getStatusCode());
  43. System.out.println(getHttpContent(response));
  44. HttpClientUtils.closeQuietly(response);
  45. }
  46. /**
  47. * 请求取消后调用该函数
  48. */
  49. @Override
  50. public void cancelled() {
  51. }
  52. /**
  53. * 请求失败后调用该函数
  54. */
  55. @Override
  56. public void failed(Exception e) {
  57. }
  58. }
  59. }

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

【转】异步的AsyncHttpClient使用详解的更多相关文章

  1. Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

    最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...

  2. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  3. 详解前端模块化工具-webpack

    webpack是一个module bundler,抛开博大精深的汉字问题,我们暂且管他叫'模块管理工具'.随着js能做的事情越来越多,浏览器.服务器,js似乎无处不在,这时,使日渐增多的js代码变得合 ...

  4. mina框架详解

     转:http://blog.csdn.net/w13770269691/article/details/8614584 mina框架详解 分类: web2013-02-26 17:13 12651人 ...

  5. AJAX请求详解 同步异步 GET和POST

    AJAX请求详解 同步异步 GET和POST 上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介绍了AJAX的概念和基本使用,附有一个小例子,下面 ...

  6. redis配置详解

    ##redis配置详解 # Redis configuration file example. # # Note that in order to read the configuration fil ...

  7. 转:AJAX中xhr对象详解

    XJAX ,并不是一种新技术的诞生.它实际上代表的是几项技术按一定的方式组合在一在同共的协作中发挥各自的作用. 它包括: 使用XHTML和CSS标准化呈现: 使用DOM实现动态显示和交互: 使用XML ...

  8. Redis快速入门详解

    Redis入门详解 Redis简介 Redis安装 Redis配置 Redis数据类型 Redis功能 持久化 主从复制 事务支持 发布订阅 管道 虚拟内存 Redis性能 Redis部署 Redis ...

  9. 78. Android之 RxJava 详解

    转载:http://gank.io/post/560e15be2dca930e00da1083 前言 我从去年开始使用 RxJava ,到现在一年多了.今年加入了 Flipboard 后,看到 Fli ...

随机推荐

  1. AWS Intro - Static IP with ssh

    Notes:  Please config static ip when launch instance. Because change dynamic public ip to static ip, ...

  2. FZU 2221—— RunningMan——————【线性规划】

     Problem 2221 RunningMan Accept: 17    Submit: 52Time Limit: 1000 mSec    Memory Limit : 32768 KB  P ...

  3. 【Shell】按行读取文件内容

    方法1:while循环中执行效率最高,最常用的方法. function while_read_LINE_bottm(){ While read LINE do echo $LINE done < ...

  4. js【jquery】-事件

    1.event对象 在IE.chrome中它是全局变量 与事件相关的信息会保存在event对象中,只有在事件发生的过程中,event才有信息 在其他浏览器中: 通过事件函数的第一个参数传入的 even ...

  5. Observer(观察者)设计模式[转]

    Observer设计模式中主要包括如下两类对象: Subject:监视对象,它往往包含着其他对象所感兴趣的内容.在本范例中,热水器就是一个监视对象,它包含的其他对象所感兴趣的内容,就是tempratu ...

  6. 数据库mysql中编码自动生成

    call PrGetRuleCodeNoDate('Table_Name'); call PrGetRuleCode('Table_Name');

  7. OC与JS交互之WebViewJavascriptBridge

    上一篇文章介绍了通过UIWebView实现了OC与JS交互的可能性及实现的原理,并且简单的实现了一个小的示例DEMO,当然也有一部分遗留问题,使用原生实现过程比较繁琐,代码难以维护.这篇文章主要介绍下 ...

  8. HTML行内元素、块状元素和行内块状元素的区分

    HTML 5 的常用元素分类 HTML可以将元素分类方式分为行内元素.块状元素和行内块状元素三种,这三者是可以互相转换的,通过display属性可以实现互相转换 (1)display:inline;转 ...

  9. es6新增的数组方法和对象

    es6新增的遍历数组的方法,后面都会用这个方法来遍历数组,或者对象,还有set,map let arr=[1,2,3,4,3,2,1,2]; 遍历数组最简洁直接的方法法 for (let value ...

  10. spark编程python实例

    spark编程python实例 ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app=PyS ...