apache异步http

依赖org.apache.httpcomponents的httpclient,httpasyncclient,httpcore-nio,httpcore

 

public class AsyncHttpGetter {
 
 private HttpAsyncClient httpAsyncClient;
 
 private final static Logger logger = Logger.getLogger(AsyncHttpGetter.class);
 
 private String serverUrl;
 
 public void init(){
  initHttpClient();
 }
 
 private void initHttpClient() {
  try {
   httpAsyncClient = new DefaultHttpAsyncClient();
   httpAsyncClient.getParams()
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
   httpAsyncClient.start();
  } catch (IOReactorException e) {
   logger.error("create HttpAsyncClient error!!");
  }
 }
 
 public void doAsyncGet(String requestUrl){
  try{
   HttpGet request = new HttpGet(requestUrl);
   httpAsyncClient.execute(request,null);
  }catch(Exception e){
   logger.error("doAsyncGet error:",e);
  }
 }
 
 public void doAsyncGet(Map<String,String> params){
  String requestUrl = buildRequestUrl(params);
  doAsyncGet(requestUrl);
 }
 
 private String buildRequestUrl(Map<String,String> params){
  StringBuilder sb = new StringBuilder(serverUrl);
  sb.append("?");
  int i = 0;
  for (Map.Entry<String, String> entry : params.entrySet()) {
   if (i++ > 0) {
    sb.append("&");
   }
   sb.append(entry.getKey()).append("=").append(entry.getValue());
  }
  return sb.toString();
 }
 
 public void destroy(){
  try {
   httpAsyncClient.shutdown();
  } catch (InterruptedException e) {
   logger.error("httpAsyncClient.shutdown:",e);
  }
 }

 public String getServerUrl() {
  return serverUrl;
 }

 public void setServerUrl(String serverUrl) {
  this.serverUrl = serverUrl;
 }
 
}

你可能感兴趣的:(apache)