`
阅读更多

 

package com.sound.haolei.base.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.sound.haolei.base.exception.HttpClientException;

import net.sf.json.JSONObject;

/**
 * httpClient工具类<br/>
 * 提供post和get的接口调用
 * 
 * @author Lvshiyang
 *
 */
public class HttpClientUtil {
	static Logger logger = LoggerFactory.getLogger("HttpClientUtil.class");
	private static final String PRO_FILE_PATH = "httpclient.properties";

	/**
	 * 超时时间,默认5000
	 */
	private static Integer timeout = 5000;
	/**
	 * 重试次数,默认3次
	 */
	private static Integer retryTimes = 3;

	/**
	 * 初始化超时时间和重试次数
	 */
	static {
		ProfileUtil profileUtil = ProfileUtil.getInstance();
		String _timeout = profileUtil.read(PRO_FILE_PATH, "client.timeout");
		String _retryTimes = profileUtil.read(PRO_FILE_PATH, "client.retry_times");
		if (!StringUtils.isEmpty(_timeout)) {
			timeout = Integer.parseInt(_timeout);
		}
		if (!StringUtils.isEmpty(_retryTimes)) {
			retryTimes = Integer.parseInt(_retryTimes);
		}
	}

	/**
	 * 创建httpClient,创建时设置超时时间和重试次数
	 * 
	 * @return
	 */
	private static CloseableHttpClient createClient() {
		HttpClientBuilder clientBuilder = HttpClients.custom();
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
				.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
		// 设置重试次数
		clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryTimes, true));
		// 设置超时时间
		clientBuilder.setDefaultRequestConfig(requestConfig);
		return clientBuilder.build();
	}

	/**
	 * 执行post请求,返回String类型的返回值
	 * @param url
	 * @param params <String,String>的Map类型参数
	 * @return
	 * @throws IOException
	 * @throws HttpClientException 
	 */
	public static String post(String url, Map<String, String> headers, Map<String, String> params) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();

		String body = null;

		logger.info("create httppost:" + url);
		HttpPost post = postForm(url,headers, params);
		try {
			body = invoke(httpclient, post);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}

		return body;
	}
	
	/**
	 * 执行post请求,返回String类型的返回值
	 * @param url
	 * @param params <String,String>的Map类型参数
	 * @return
	 * @throws IOException
	 * @throws HttpClientException 
	 */
	public static String post(String url, Map<String, String> headers) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();
		
		String body = null;

		logger.info("create httppost:" + url);
		HttpPost httpost = new HttpPost(url);
		
		if (null != headers) {
			for (String key : headers.keySet()) {
				httpost.setHeader(key, headers.get(key));
			}
		}
		try {
			body = invoke(httpclient, httpost);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}
		return body;
	}
	
	/**
	 * 执行post请求,返回String类型的返回值 设置cookie
	 * @param url
	 * @param params <String,String>的Map类型参数
	 * @return
	 * @throws IOException
	 * @throws HttpClientException 
	 */
	public static String postAndCookie(String url, Map<String, String> headers,Map<String,String> cookieMap) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();
		String body = null;

		logger.info("create httppost:" + url);
		HttpPost httpost = new HttpPost(url);
		StringBuilder cookieStr = new StringBuilder(); 
		if(null != cookieMap){
			for(Entry<String, String> entry : cookieMap.entrySet()){
				String name = entry.getKey();
				String value = entry.getValue();
				cookieStr.append(name).append('=').append(value).append(';');  
			}
			cookieStr.deleteCharAt(cookieStr.length() - 1);
		}
		if (null != headers) {
			for (String key : headers.keySet()) {
				httpost.setHeader(key, headers.get(key));
				httpost.setHeader("Cookie", cookieStr.toString());
			}
		}
		
		try {
			body = invoke(httpclient, httpost);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}
		return body;
	}

	/**
	 * 执行get请求,返回String类型的请求
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	public static String get(String url) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();
		String body = null;
		logger.info("create httpget:" + url);
		HttpGet get = new HttpGet(url);
		try {
			body = invoke(httpclient, get);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}

		return body;
	}
	
	/**
	 * 执行get请求,返回String类型的请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	public static String getOfParams(String url,Map<String,String> params) throws IOException, HttpClientException {
		 if (params != null&&params.size() > 0) {
	            StringBuffer sb = new StringBuffer();
	            if (url.indexOf("?") == -1) {
	                url += "?";
	            } else {
	                url += "&";
	            }
	            for (ConcurrentHashMap.Entry<String, String> entry : params.entrySet()) {
	                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
	            }
	            url += sb.substring(0, sb.length() - 1);
	        }
		 return get(url);
	}

	
	
	/**
	 * 执行get请求,返回String类型的请求
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	public static String get(String url,Map<String,String> headers) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();
		String body = null;
		logger.info("create httpget:" + url);
		HttpGet get = new HttpGet(url);
		if (null != headers) {
			for (String key : headers.keySet()) {
				get.setHeader(key, headers.get(key));
			}
		}
		try {
			body = invoke(httpclient, get);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}

		return body;
	}
	
	/**
	 * 执行get请求,返回String类型的请求
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	public static String getAndCookie(String url,Map<String,String> headers,Map<String,String> cookieMap) throws IOException, HttpClientException {
		CloseableHttpClient httpclient = createClient();
		
		String body = null;
		logger.info("create httpget:" + url);
		HttpGet get = new HttpGet(url);
		
		StringBuilder cookieStr = new StringBuilder(); 
		if(null != cookieMap){
			for(Entry<String, String> entry : cookieMap.entrySet()){
				String name = entry.getKey();
				String value = entry.getValue();
				cookieStr.append(name).append('=').append(value).append(';');  
			}
			cookieStr.deleteCharAt(cookieStr.length() - 1);
		}
		if (null != headers) {
			for (String key : headers.keySet()) {
				get.setHeader(key, headers.get(key));
				get.setHeader("Cookie", cookieStr.toString());
			}
		}
		try {
			body = invoke(httpclient, get);
		} catch (HttpClientException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new HttpClientException(404);
		} catch (Exception e) {
			throw e;
		} finally {
			httpclient.close();
		}

		return body;
	}

	/**
	 * 调用请求
	 * 
	 * @param httpclient
	 * @param httpost
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	private static String invoke(CloseableHttpClient httpclient, HttpUriRequest httpost)
			throws IOException, HttpClientException {
		// 发送请求
		CloseableHttpResponse response = sendRequest(httpclient, httpost);
		/*String body = null;
		try {
			// 解析返回
			body = paseResponse(response);
			response.close();
		} catch (HttpClientException e) {
			e.printStackTrace();
		} finally {
			response.close();
		}
		return body;*/
		
		return paseResponse(response);
	}

	/**
	 * 解析返回结果
	 * 
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws HttpClientException
	 */
	private static String paseResponse(HttpResponse response) throws IOException, HttpClientException {
		logger.info("get response from http server..");
		String body = null;
		HttpEntity entity = response.getEntity();
		logger.info("response status: " + response.getStatusLine());
		// 获取状态码
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode == 200) {
			body = EntityUtils.toString(entity,"utf-8");
			logger.info(body);
			EntityUtils.consume(entity);
		} else {
			throw new HttpClientException(statusCode);
		}
		return body;
	}

	/**
	 * 发送请求
	 * 
	 * @param httpclient
	 * @param httpost
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	private static CloseableHttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpost) throws ClientProtocolException, IOException {

		CloseableHttpResponse response = httpclient.execute(httpost);
		return response;
	}

	/**
	 * 构建HttpPost
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static HttpPost postForm(String url, Map<String, String> headers, Map<String, String> params) {

		HttpPost httpost = new HttpPost(url);
		/**
		 * 2018年5月30日10:38:48
		 * wangruwei
		 * 请求变成短连接
		 */
		httpost.setProtocolVersion(HttpVersion.HTTP_1_0);
		httpost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}

		if (null != headers) {
			for (String key : headers.keySet()) {
				httpost.setHeader(key, headers.get(key));
			}

		}

		try {

			logger.info("set utf-8 form entity to httppost");
			httpost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return httpost;
	}
	
	/**
	 * 
	 * @Title: doPost 
	 * @Description: json post提交
	 * @param url
	 * @param headers
	 * @param json
	 * @return    设定文件 
	 * JSONObject    返回类型 
	 * @throws 
	 * @author Lvshiyang
	 * @date 2017年5月11日 上午10:35:09
	 */
	public static JSONObject doJsonPost(String url,Map<String, String> headers,JSONObject json){
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        if (null != headers) {
			for (String key : headers.keySet()) {
				post.setHeader(key, headers.get(key));
			}

		}
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(),"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType\
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }

}

 

 

client.timeout=10000
client.retry_times=5

 

 

 

分享到:
评论

相关推荐

    HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件

    下面我们将详细讨论HttpClientUtil工具类如何实现这些功能。 首先,HttpClientUtil工具类通常会封装HttpClient的基本操作,以便于开发者在应用中便捷地调用。GET和POST请求是HTTP协议中最常见的两种请求方法。GET...

    http请求工具类HttpClientUtil,get,post请求(csdn)————程序.pdf

    1. **HttpClientUtil 类结构**: 类中定义了一个静态的日志器 LOGGER,用于记录执行过程中的信息,使用的是 SLF4J 日志框架。此外,创建了一个静态的 `CloseableHttpClient` 实例 `client`,这是 HttpClient 的核心...

    httpClientUtil工具类

    httpClientUtil工具类

    HttpClientUtil.java

    HttpClientUtil请求第三方接口,可以直接使用,post请求方式、get请求方式都有,直接粘贴复制就ok

    HttpClientUtil工具类,调用第三方接口

    该工具类是java 调用第三方接口时需要使用到的。HttpClientUtil 包含get和post方法。

    httpclientutil

    在"HttpClientUtil2-发送json返回json测试通过.java"这个文件中,我们可以预见到这是一个实现了发送JSON数据并接收JSON响应的示例。以下是一些关键知识点: 1. **Apache HttpClient 库**:HttpClient 是 Apache ...

    HttpClientUtil4.java

    HttpClientUtil4.java 工具类

    HttpClientUtil工具类 里面包含GET POST 及返回值处理

    - **实例化HttpClientUtil**:在代码中创建HttpClientUtil的实例。 - **调用方法**:根据需求,调用GET或POST方法,传入必要的参数(如URL、请求头、请求体等)。 - **处理返回值**:获取到的返回值通常是一个...

    httpclientUtil

    1.基于HttpClient-4.4.1封装的一个工具类; 2.基于HttpAsycClient-4.1封装的异步HttpClient工具类; 3.javanet包下面是基于jdk自带的UrlConnection进行封装的。 前2个工具类支持插件式配置Header、插件式配置...

    httpClientUtil

    自己做项目中用到的,以后保存下来以防以后用到。多多积累。

    HttpClientUtil2.java

    HttpClient汇总工具类 HttpClient汇总工具类HttpClient汇总工具类HttpClient汇总工具类

    Java Http工具类HttpClientUtil

    多年积累,功能比较强大,可设置路由连接数,时间,请求类型包括get,post, 参数包括urlcode,map,json,xml。注释很清楚。

    基于jmeter+Java+HttpclientUtil实现的接口测试工具

    基于jmeter+Java+HttpclientUtil实现的接口测试工具,通过Excel表格进行维护接口相关参数信息,借助Jmeter工具通过java请求设计接口测试自动化测试用例。代码重写了JavaSampleClient类,在使用过程中取出了冗余的...

Global site tag (gtag.js) - Google Analytics