`

HttpClient实例

阅读更多
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.http.Consts;
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.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class HttpClient {

	private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

	public static String utf8 = "utf-8";
	
	private static String userAgentName = "User-Agent";
	private static String userAgentValue = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) "
			+ "Gecko/20100101 Firefox/45.0";

	private String userAgent = null;
	
	public void setUserAgent(String userAgent) {
		this.userAgent = userAgent;
	}

	private static TrustManager manager = new X509TrustManager() {

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub

		}
	};

	private static PoolingHttpClientConnectionManager connectionManager = null;

	// 路由(MAX_PER_ROUTE)是对最大连接数(MAX_TOTAL)的细分,整个连接池的限制数量实际使用DefaultMaxPerRoute并非MaxTotal。
	// 设置过小无法支持大并发(ConnectionPoolTimeoutException: Timeout waiting for
	// connection from pool)
	static {

		try {
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new TrustManager[] { manager }, null);
			SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
					NoopHostnameVerifier.INSTANCE);
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
					.<ConnectionSocketFactory>create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", socketFactory)
					.build();
			connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			connectionManager.setMaxTotal(50);// 将最大连接数增加到50
			connectionManager.setDefaultMaxPerRoute(5);// 设置路由最大连接数
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage());
		} catch (KeyManagementException e) {
			logger.error(e.getMessage());
		}

	}
	CloseableHttpClient httpsClient = null;

	private void create() {
		RequestConfig defaultRequestConfig = RequestConfig.custom()
				.setCookieSpec(CookieSpecs.STANDARD_STRICT)
				.setExpectContinueEnabled(true)
				.setConnectionRequestTimeout(5000)
				.setConnectTimeout(10000)
				.setSocketTimeout(10000)
				.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
				.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
		HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> {
			if (executionCount >= 3) {// 如果已经重试了5次,就放弃                     
                return false;
            }  
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试                    
                return true;
            }  
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常                   
                return false;
            }                 
            if (exception instanceof InterruptedIOException) {// 超时                   
                return false;
            }  
            if (exception instanceof UnknownHostException) {// 目标服务器不可达                   
                return false;
            }  
            if (exception instanceof ConnectTimeoutException) {// 连接被拒绝                   
                return false;
            }  
            if (exception instanceof SSLException) {// ssl握手异常                    
                return false;
            }  
              
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            // 如果请求是幂等的,就再次尝试  
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }  
            return false;
		};
		httpsClient = HttpClients.custom()
				.setConnectionManager(connectionManager)
				.setDefaultRequestConfig(defaultRequestConfig)
				.setRetryHandler(httpRequestRetryHandler)
				.build();

	}
	
	public void close() {
		try {
			if(httpsClient != null) {
				httpsClient.close();
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}

	private HttpClient() {
		create();
	}

	public static HttpClient createHttpsClient() {
		return new HttpClient();
	}

	private Result toResult(CloseableHttpResponse response) throws IOException {
		Result result = null;
		try {
			String body = EntityUtils.toString(response.getEntity(), HttpClient.utf8);
			result = new Result();
			result.setBody(body);
			result.setStatus(response.getStatusLine().getStatusCode());
			if (logger.isDebugEnabled()) {
				logger.debug("https result: {}", result);
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return result;
	}

	/**
	 * post 不带参数请求, CloseableHttpResponse 需要调用方关闭
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public CloseableHttpResponse doHttpsPost(String url) throws IOException {
		return doHttpsPost(url, (List<NameValuePair>) null);
	}

	/**
	 * post 不带参数请求
	 * 
	 * @param url
	 * @return Result 返回带字符串响应结果和响应状态的对象
	 * @throws IOException
	 */
	public Result doHttpsPostReturnResult(String url) throws IOException {
		return toResult(doHttpsPost(url));
	}

	/**
	 * post 不带参数,返回对象,响应结果必须是json 对象
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> T doHttpsPostReturnObject(String url, Class<T> c) throws IOException {
		T result = null;
		Result response = doHttpsPostReturnResult(url);
		result = JSON.parseObject(response.getBody(), c);
		return result;
	}

	/**
	 * 不带参数,返回集合,响应结果必须是json 数组
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> List<T> doHttpsPostReturnArray(String url, Class<T> c) throws IOException {
		List<T> result = null;
		Result response = doHttpsPostReturnResult(url);
		result = JSON.parseArray(response.getBody(), c);
		return result;
	}

	public CloseableHttpResponse doHttpsPost(String url, Map<String, Object> params) 
			throws IOException {
		List<NameValuePair> values = new ArrayList<>();
		if (params != null) {
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair p = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				values.add(p);
			}
		}
		return doHttpsPost(url, values);
	}

	/**
	 * post 任意键值对数据
	 * 
	 * @param url
	 * @return Result 返回带字符串响应结果和响应状态的对象
	 * @throws IOException
	 */
	public Result doHttpsPostReturnResult(String url, Map<String, Object> params) throws IOException {
		return toResult(doHttpsPost(url, params));
	}

	/**
	 * post 任意键值对数据,返回对象,响应结果必须是json 对象
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> T doHttpsPostReturnObject(String url, Map<String, Object> params, Class<T> c) 
			throws IOException {
		T result = null;
		Result response = doHttpsPostReturnResult(url, params);
		result = JSON.parseObject(response.getBody(), c);
		return result;
	}

	/**
	 * post 键值对数据,返回集合,响应结果必须是json 数组
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> List<T> doHttpsPostReturnArray(String url, Map<String, Object> params, Class<T> c) 
			throws IOException {
		List<T> result = null;
		Result response = doHttpsPostReturnResult(url, params);
		result = JSON.parseArray(response.getBody(), c);
		return result;
	}

	public CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values) throws IOException {
		HttpPost post = new HttpPost(url);
		if (values != null) {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
			post.setEntity(entity);
		}
		RequestConfig requestConf = RequestConfig.custom()
				.setSocketTimeout(10000)
				.setConnectTimeout(10000)
				.build();
		post.setConfig(requestConf);
		setCommonHeader(post);
		CloseableHttpResponse response = httpsClient.execute(post);
		return response;
	}

	/**
	 * post NameValuePair键值对参数
	 * 
	 * @param url
	 * @return Result 返回带字符串响应结果和响应状态的对象
	 * @throws IOException
	 */
	public Result doHttpsPostReturnResult(String url, List<NameValuePair> values) throws IOException {
		return toResult(doHttpsPost(url, values));
	}

	/**
	 * post NameValuePair键值对参数
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> T doHttpsPostReturnObject(String url, List<NameValuePair> values, Class<T> c) 
			throws IOException {
		T result = null;
		Result response = doHttpsPostReturnResult(url, values);
		result = JSON.parseObject(response.getBody(), c);
		return result;
	}

	/**
	 * post NameValuePair键值对参数
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> List<T> doHttpsPostReturnArray(String url, List<NameValuePair> values, Class<T> c) 
			throws IOException {
		List<T> result = null;
		Result response = doHttpsPostReturnResult(url, values);
		result = JSON.parseArray(response.getBody(), c);
		return result;
	}

	public CloseableHttpResponse doHttpsPost(String url, String values) throws IOException {
		HttpPost post = new HttpPost(url);
		if (values != null) {
			StringEntity entity = new StringEntity(values, Consts.UTF_8);
			post.setEntity(entity);
		}
		setCommonHeader(post);
		CloseableHttpResponse response = httpsClient.execute(post);
		return response;
	}

	/**
	 * post 任何字符串数据,包括json等
	 * 
	 * @param url
	 * @return Result 返回带字符串响应结果和响应状态的对象
	 * @throws IOException
	 */
	public Result doHttpsPostReturnResult(String url, String values) throws IOException {
		return toResult(doHttpsPost(url, values));
	}

	/**
	 * post 任何字符串数据,包括json等,返回对象,响应结果必须是json 对象
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> T doHttpsPostReturnObject(String url, String values, Class<T> c) throws IOException {
		T result = null;
		Result response = doHttpsPostReturnResult(url, values);
		result = JSON.parseObject(response.getBody(), c);
		return result;
	}

	/**
	 * post 任何字符串数据,包括json等,响应结果必须是json 数组
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> List<T> doHttpsPostReturnArray(String url, String values, Class<T> c) throws IOException {
		List<T> result = null;
		Result response = doHttpsPostReturnResult(url, values);
		result = JSON.parseArray(response.getBody(), c);
		return result;
	}

	public CloseableHttpResponse doHttpsGet(String url) throws IOException {
		HttpGet get = new HttpGet(url);
		RequestConfig requestConf = RequestConfig.custom()
				.setSocketTimeout(10000)
				.setConnectTimeout(10000)
				.build();
		get.setConfig(requestConf);
		setCommonHeader(get);
		CloseableHttpResponse response = httpsClient.execute(get);
		return response;
	}

	/**
	 * post 不带参数请求
	 * 
	 * @param url
	 * @return Result 返回带字符串响应结果和响应状态的对象
	 * @throws IOException
	 */
	public Result doHttpsGetReturnResult(String url) throws IOException{
		return toResult(doHttpsGet(url));
	}

	/**
	 * post 不带参数,返回对象,响应结果必须是json 对象
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> T doHttpsGetReturnObject(String url, Class<T> c) throws IOException {
		T result = null;
		Result response = doHttpsGetReturnResult(url);
		result = JSON.parseObject(response.getBody(), c);
		return result;
	}

	/**
	 * 不带参数,返回集合,响应结果必须是json 数组
	 * 
	 * @param url
	 * @param c
	 * @return
	 * @throws IOException
	 */
	public <T> List<T> doHttpsGetReturnArray(String url, Class<T> c) throws IOException {
		List<T> result = null;
		Result response = doHttpsGetReturnResult(url);
		result = JSON.parseArray(response.getBody(), c);
		return result;
	}

	private void setCommonHeader(HttpRequestBase request) {
		if(userAgent == null) {
			request.setHeader(userAgentName, userAgentValue);
		} else {
			request.setHeader(userAgentName, userAgent);
		}
		
	}
	
	public static class Result {
		private String body;
		private Integer status;

		public String getBody() {
			return body;
		}

		public void setBody(String body) {
			this.body = body;
		}

		public Integer getStatus() {
			return status;
		}

		public void setStatus(Integer status) {
			this.status = status;
		}

		@Override
		public String toString() {
			return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
		}

	}
	
}
分享到:
评论

相关推荐

    httpClient实例

    自己做的httpClient实例,写的比较多刚接触的可以看看

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    要创建一个简单的HttpClient实例,你需要以下步骤: 1. 引入Apache HttpClient库: 在你的项目中,确保已经添加了Apache HttpClient的依赖。例如,如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```...

    HttpClient实例+必备3个jar包

    在"HttpClient实例+必备3个jar包"的项目中,包含了以下关键知识点: 1. **HttpClient类库**:HttpClient库提供了丰富的API,可以创建复杂的HTTP请求,包括设置请求头、携带请求体、处理重定向、管理Cookie等。通过...

    C#HTTPclient 实例应用

    // 从依赖注入容器中获取HttpClient实例 var httpClient = serviceProvider.GetService&lt;HttpClient&gt;(); ``` ### 2. 发送GET请求 `HttpClient`提供了`GetAsync`方法用于发送GET请求。下面是如何使用它的示例: ```...

    httpclient的入门实例

    1. **创建HttpClient实例**:使用`HttpClientBuilder`或`HttpClients`静态工厂方法创建一个HttpClient实例。 ```java HttpClient httpClient = HttpClients.createDefault(); ``` 2. **构建HttpRequest**:...

    httpclient实例

    实现调用远程servlet方法的实例。有详细注释。和依赖jar包。 //servlet路径 String url = "http://localhost:8080/zfw/servlet/CustomQueryServlet"; //参数一为表名,参数二为字段名 String params[] = {"ZC_...

    JavaHttpClient实例

    本实例将深入探讨如何在Java中使用HttpClient进行网络通信。 首先,你需要在项目中引入HttpClient的相关依赖。如果是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml &lt;groupId&gt;org.apache.httpcomponents ...

    HttpClient实例_001_初步实现项目01的servlet,与项目02的servlet,之间数据访问

    创建一个HttpClient实例,然后创建一个请求方法对象(GET或POST),设置URL和其他参数。以下是一个简单的GET请求示例: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ...

    httpClient 网络传输的实例

    1. **创建HttpClient对象**:首先,我们需要创建一个HttpClient实例,这通常是通过HttpClientBuilder或HttpAsyncClientBuilder构建的。例如: ```java CloseableHttpClient httpClient = HttpClients.create...

    HttpClient模拟登录实例

    创建HttpClient实例是模拟登录的第一步。这可以通过`HttpClientBuilder`或直接使用`HttpClient`的静态工厂方法完成。例如: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. **...

    【ASP.NET编程知识】.NET CORE HttpClient的使用方法.docx

    命名客户端是指我们可以给 HttpClient 实例起一个名称,以便在后续的使用中可以根据名称来获取对应的 HttpClient 实例。我们可以使用以下代码来添加命名客户端: `services.AddHttpClient(Constants.SERVICE_USER...

    httpClient4.3.6包和实例

    1. **HttpClient实例**:HttpClient是线程不安全的,所以通常推荐每个请求创建一个新实例。`HttpClientBuilder`类可以用来构建自定义配置的客户端实例。 2. **请求执行器(RequestExecutor)**:处理HTTP请求和响应...

    jsp 中HttpClient中的POST方法实例详解.docx

    1. **创建HttpClient实例和PostMethod实例** ```java String url = ".newsmth.net/bbslogin2.php"; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); ``` 2. **设置...

    HttpClient应用实例2

    读者将学习到如何配置HttpClient实例,设置请求参数,处理响应,并通过源码分析了解其实现细节。同时,还会接触到日志管理和编码转换的相关知识,这些都是Java开发中与网络通信密切相关的技能。

    httpclient httpclient.jar

    通常,我们创建一个HttpClient实例,并设置其配置参数,如连接超时、重试策略等。 2. **HttpHost**:表示目标HTTP服务器的信息,包括主机名、端口和协议(HTTP或HTTPS)。 3. **HttpGet/HttpPost**:这些是执行...

    httpclient模拟登录实例

    6. **连接管理和释放资源**:为了防止资源泄露,我们需要关闭HTTP连接和释放HttpClient实例。 ```java response.close(); httpClient.close(); ``` 在实际应用中,模拟登录可能涉及到更复杂的情况,如验证码处理、...

    httpclient.zip

    2. 创建HTTPClient实例:根据需求配置连接池、超时时间、重试策略等。 3. 注册到Spring容器:将HTTPClient实例作为bean注入到Spring的IoC容器中。 4. 使用HTTPClient:在需要发送HTTP请求的类中,通过@Autowired注解...

    httpclient

    通过HttpClient实例,我们可以配置连接管理、重试策略、超时设置等高级特性。 2. **HttpHost对象**:表示目标服务器的信息,包括主机名、端口号和协议类型(HTTP或HTTPS)。 3. **HttpRequest与HttpResponse**:...

Global site tag (gtag.js) - Google Analytics