栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

HttpClient工具类(支持多线程高并发)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

HttpClient工具类(支持多线程高并发)

今天在使用HttpClient的时候由于使用了多线程,所以出现了如下报错:

I/O exception (java.net.BindException) caught when processing request to

于是最后改用连接池来创建httpClient 解决了这个问题,避免资源一直占用不释放的问题。

下面贴出两个工具类的代码供大家比较:

改造前的代码:
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;

@Component
public class HttpClientUtils {
	private static Logger logger = Logger.getLogger(HttpClientUtils.class);

	private static final int TIMEOUT = Integer.MAX_VALUE; //30*60,半小时
	
	
	
	private static HttpClientUtils httpClientUtils;  // 静态初使化当前类
	
	@PostConstruct 
    public void init() {
		httpClientUtils = this;
 
    }

	public static String postRequest(String httpUrl, Map args) {
		
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		logger.info("httpUrl:" + httpUrl);
		try {
			//1、
			HttpClientBuilder hcb = HttpClientBuilder.create();
			RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT * 1000).build();
			hcb.setDefaultRequestConfig(config);
			//2、
			httpClient = hcb.build();
			
			//3、设置URL
			HttpPost httpPost = new HttpPost(httpUrl);
			
			//4、声明存放参数的List集合
            List params = new ArrayList();
            Set> entrySet = args.entrySet();
			for (Entry entry : entrySet) {
				if(entry.getValue()!=null) {
					params.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
				}else {
					params.add(new BasicNameValuePair(entry.getKey(), null));
				}
			}
			
			//5、创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
 
            //6、把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);

			//7、执行
			response = httpClient.execute(httpPost);
			
			//8、 获得响应的实体对象
			HttpEntity entity = response.getEntity();
			
			String responseBody = null;
			if (entity != null) {
				responseBody = EntityUtils.toString(entity, "UTF-8");
				//关闭流
				EntityUtils.consumeQuietly(entity);
			}
			return responseBody;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
	
	
}

改造后的代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
 
public class WebTools {
 
    public static String KEY_STATUS_CODE = "statusCode";
    public static String KEY_CONTENT = "content";
    private static Logger logger = Logger.getLogger(WebTools.class);
    private static WebTools webTools;  // 静态初使化当前类
    
    @PostConstruct 
    public void init() {
    	webTools = this;
 
    }
    
    
    
    private final static PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager();  //连接池管理器
    private final static HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {  //retry handler
        public boolean retryRequest(IOException exception,
                                    int executionCount, HttpContext context) {
            if (executionCount >= 5) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                return false;
            }
            if (exception instanceof UnknownHostException) {
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                return false;
            }
            HttpClientContext clientContext = HttpClientContext
                    .adapt(context);
            HttpRequest request = clientContext.getRequest();
 
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
 
    static {   //类加载的时候 设置最大连接数 和 每个路由的最大连接数
        poolConnManager.setMaxTotal(2000); 
        poolConnManager.setDefaultMaxPerRoute(1000);
    }
 
 
    
    private static CloseableHttpClient getCloseableHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setRetryHandler(httpRequestRetryHandler)
                .build();
 
        return httpClient;
    }
 
    
    private static Map buildResultMap(CloseableHttpResponse response, HttpEntity entity) throws
            IOException {
        Map result;
        result = new HashMap<>(2);
        result.put(KEY_STATUS_CODE, response.getStatusLine().getStatusCode());  //status code
        if (entity != null) {
            result.put(KEY_CONTENT, EntityUtils.toString(entity, "UTF-8")); //message content
        }
        return result;
    }
 
    public static String postRequest(String httpUrl, Map args) {
		
        CloseableHttpClient httpClient = getCloseableHttpClient();
        logger.info("httpUrl:" + httpUrl);
        HttpPost httpPost = new HttpPost(httpUrl);
        CloseableHttpResponse response = null;
        try {
 
        	//4、声明存放参数的List集合
            List params = new ArrayList();
            Set> entrySet = args.entrySet();
			for (Entry entry : entrySet) {
				if(entry.getValue()!=null) {
					params.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
				}else {
					params.add(new BasicNameValuePair(entry.getKey(), null));
				}
			}
			//5、创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            //6、把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
            
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseBody = null;
			if (entity != null) {
				responseBody = EntityUtils.toString(entity, "UTF-8");
				//关闭流
				EntityUtils.consumeQuietly(entity);
			}
			return responseBody;
 
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		
	}
    
    
    public static Map postJson(String url, String message) {
 
        Map result = null;
        CloseableHttpClient httpClient = getCloseableHttpClient();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
 
            httpPost.setHeader("Accept", "application/json;charset=UTF-8");
            httpPost.setHeader("Content-Type", "application/json");
 
            StringEntity stringEntity = new StringEntity(message);
            stringEntity.setContentType("application/json;charset=UTF-8");
 
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = buildResultMap(response, entity);
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

使用改造后的代码就不会再报上面出现的错误了,多线程HttpClient也正常运行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/918807.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号