HttpClient
1、get 有参
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 1、有参数-拼接 2、无参直接过
StringBuffer params = new StringBuffer();
try {
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name=" + URLEncoder.encode("&", "utf-8"));
params.append("&");
params.append("age=24");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 创建Get请求
HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
2、post有参
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
1、表单模式------------------------------
// 创建参数列表-
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
2、json模式----------------------------
HttpEntity entity= new StringEntity(json, ContentType.APPLICATION_JSON)
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
工具类
public class HttpClientUtil {
/**
* 连接池
*/
private static PoolingHttpClientConnectionManager cm;
/**
* 请求对象
*/
private static RequestConfig config;
/**
* 组装http请求header上的参数
* @param header
* @return
*/
private static HttpRequestBase parseHttpHeader(Map<String, Object> header, HttpRequestBase requestBase){
if(!ValidateUtil.isEmpty(header)){
for (String key :header.keySet()){
requestBase.addHeader(key, String.valueOf(header.get(key)));
}
}
return requestBase;
}
/*********************************************************
*
*/
/**
* 根据参数获取Client对象
* @param cg 配置参数
* @return
*/
public static CloseableHttpClient getHttpClient(RequestConfig cg){
if(ValidateUtil.isEmpty(cg)){
cg = config;
}
return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(cg).build();
}
/**
*
* @param requestBase 连接对象
* @param config 配置参数
* @return
*/
private static String getResult(HttpRequestBase requestBase, RequestConfig config){
HttpEntity httpEntity = null;
CloseableHttpClient httpClient = getHttpClient(config);
try(CloseableHttpResponse response = httpClient.execute(requestBase)) {
httpEntity = response.getEntity();
return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
consume(httpEntity);
}
return "";
}
private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
static {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(300);
cm.setDefaultMaxPerRoute(60);
config = RequestConfig.custom().setConnectTimeout(5*1000)
.setSocketTimeout(60*1000)
.setConnectionRequestTimeout(1000).build();
}
/**
* 释放连接
* @param entity 返回实体对象
*/
private static void consume(HttpEntity entity){
try {
EntityUtils.consume(entity);
} catch (IOException e) {
log.error("释放http连接的时候发生异常", e);
}
}