HttpClient同期呼び出しHttpAsyncClient非同期呼び出し


公式サイトのサンプルアドレス: http://hc.apache.org/httpcomponents-asyncclient-4.1.x/index.html
必要なjarバッグ:maven倉庫の下に行けばいい
httpasyncclient
httpclient
httpcore
httpcore-nio

 
HttpClient同步调用 与 HttpAsyncClient 异步调用_第1张图片
1:同期呼び出し 
post
/**
	 * 
	 * doPost   HTTP POST     WebService
	 * 
	 * @param url   
	 * @param parameters   
	 * @return String 
	 */
	public static String doPost(String url, List parameters) {
		//   httpclient
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//      
		RequestConfig config = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
		
		//   httppost
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(config);
		//   EntityBuilder
		EntityBuilder builder = EntityBuilder.create();
		//   ContentType    application/x-www-form-urlencoded
		builder.setContentType(ContentType.create("application/x-www-form-urlencoded"));
		//         builder 
		builder.setParameters(parameters);
		//   HttpEntity
		HttpEntity entity = builder.build();
		//   entity httppost
		httpPost.setEntity(entity);
		String result = "";
		try {
			//   httppost  ,  httpResponse  
			HttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			//   200
			if (statusCode == HttpStatus.SC_OK) {
				InputStream is = response.getEntity().getContent();
				//      String
				result = getStreamAsString(is);
			}else{
				logger.error("  WebService      ",url,statusCode);	
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("  WebService       ,              ",url,e.getMessage());
		} catch (ClientProtocolException e) {
			logger.error("  WebService       ,              ",url,e.getMessage());
		} catch (IOException e) {
			logger.error("  WebService      ",url,e);
		} finally {
			//   httpclient
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 
	 * getStreamAsString       String
	 * 
	 * @param stream    
	 * @return
	 * @throws IOException
	 */
	private static String getStreamAsString(InputStream stream) throws IOException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
			StringWriter writer = new StringWriter();
			char[] chars = new char[8192];
			int count = 0;
			while ((count = reader.read(chars)) > 0) {
				writer.write(chars, 0, count);
			}
			return writer.toString();
		} finally {
			if (null != stream) {
				stream.close();
			}
		}
	}

 
get

package com.fr.data;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/** 
 * ClassName: HttpClientRequest
 * Function: TODO ADD FUNCTION. 
 * date: 2019 4 18    4:58:00
 * 
 * @author cf 
 */
public class HttpClientRequest {
    //     
    private static final HttpClient client = HttpClients.custom().build();

    /**
    *
    * (post)
    *
    * @param map   
    * @return     
    * @throws Exception
    * @author tangjiandong
    */
   public static  JSONObject get(String url)
   {
          HttpGet get = new HttpGet(url);

          //         
          RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
       get.setConfig(config);
       JSONObject obj = null;
       try{
               HttpResponse  response = client.execute(get);
           if(200 == response.getStatusLine().getStatusCode())
           {
               obj = JSONObject.parseObject(new String(EntityUtils.toString(response.getEntity()).getBytes("iso8859-1"), "UTF-8"));
           }
       }catch (IOException e) {
           return null;
       }catch (Exception e) {
           return null;
       }{
           //    
               get.releaseConnection();
       }
       return obj;
   }
}

 
2:非同期呼び出し
/** 
 * Project Name:finereport10 
 * File Name:HttpClientRequest.java 
 * Package Name:com.fr.data 
 * Date:2019 4 18    4:58:00 
 * Copyright (c) 2019,            All Rights Reserved. 
 * 
 */
package com.fr.data;

import java.io.IOException;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/** 
 * ClassName: HttpClientRequest
 * Function: TODO ADD FUNCTION. 
 * date: 2019 4 18    4:58:00
 * 
 * @author cf 
 */
public class HttpClientRequest {
	
	private static final int socketTimeout = 2000; //        
	private static final int connectTimeout = 6000; //      
	private static final int requestTimeout = 2000; //         
	

	
	private static   RequestConfig config = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout).build();
	
	private static CloseableHttpAsyncClient asyncClient = HttpAsyncClients.custom().setDefaultRequestConfig(config).build();
	
	

	/**
    *
    * (get)
    *
    * @param map   
    * @return     
    * @throws Exception
    * @author tangjiandong
    */
   public static  JSONObject get(String url)
   {
   	   HttpGet get = new HttpGet(url);
   	   RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout).setSocketTimeout(socketTimeout).build();
       get.setConfig(config);
      
       JSONObject obj = null;
  	 
  		try {
  			asyncClient.start();
       		HttpResponse httpResponse = asyncClient.execute(get, null).get();
       	
			if (200 == httpResponse.getStatusLine().getStatusCode()) {
					obj = JSONObject.parseObject(new 
                      String(EntityUtils.toString(httpResponse.getEntity()).getBytes(
							"iso8859-1"), "UTF-8"));
				}
			} catch (IOException e) {
				return null;
			} catch (Exception e) {
				return null;
			} finally {
				//     
				get.releaseConnection();
				try {
					asyncClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
       
       return obj;
   }

   

   
}