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

   

   
}




 

你可能感兴趣的:(程序人生)