只是项目中有用到,目前该方案并不是很完善,如果各位在使用中有遇到什么问题或者有改进的方案可以留言,或作分享(仅供测试参考)
一、依赖jar包
<!-- 第三方网络请求工具 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.57</version> </dependency>
二、请求工具类编写
package com.demo.httputil; import lombok.extern.slf4j.Slf4j; import org.apache.http.NameValuePair; 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.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author 咦!一只菜鸡 * @version 1.0 * @desrc */ @Slf4j public class HttpClientUtils { private static final String REQUEST_ENCODING="UTF-8"; private static final String METHOD_GET="get"; private static final String METHOD_POST="post"; private static final int TIMEOUT=15*1000; /** * 三方接口请求 * @param url 请求地址 * @param type 请求类型 * @param encoding 请求编码格式 * @param params 请求参数Map * @param heads 请求头参数 * @param timeOut 请求超时时间 * @return */ public static Object httpRequest(String url,String type,String encoding,Map<String,Object> params,Map<String,Object> heads,int timeOut){ if(METHOD_GET.equalsIgnoreCase(type)){ return sendGet(url,encoding,params,heads,timeOut); }else if(METHOD_POST.equalsIgnoreCase(type)){ return sendPost(url,encoding,params,heads,timeOut); } return "暂不支持该请求方式"; } /** * 三方接口请求 * @param url 请求地址 * @param type 请求类型 * @param encoding 请求编码格式 * @param params 请求参数Map * @param heads 请求头参数 * @return */ public static Object httpRequest(String url,String type,String encoding,Map<String,Object> params,Map<String,Object> heads){ if(METHOD_GET.equalsIgnoreCase(type)){ return sendGet(url,encoding,params,heads,TIMEOUT); }else if(METHOD_POST.equalsIgnoreCase(type)){ return sendPost(url,encoding,params,heads,TIMEOUT); } return "暂不支持该请求方式"; } /** * 三方接口请求 * @param url 请求地址 * @param type 请求类型 * @param params 请求参数Map * @return */ public static Object httpRequest(String url,String type,Map<String,Object> params){ if(METHOD_GET.equalsIgnoreCase(type)){ return sendGet(url,REQUEST_ENCODING,params,null,TIMEOUT); }else if(METHOD_POST.equalsIgnoreCase(type)){ return sendPost(url,REQUEST_ENCODING,params,null,TIMEOUT); } return "暂不支持该请求方式"; } public static Object sendGet(String url){ return sendGet(url,"utf-8",null,null,TIMEOUT); } public static Object sendGet(String url, String encoding, Map<String,Object> params,Map<String,Object> heads,int timeOut){ //创建httpClient对象 CloseableHttpClient httpClient= HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (!ObjectUtils.isEmpty(params)) { for (String key : params.keySet()) { builder.addParameter(key, params.get(key).toString()); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); //设置请求超时时间 RequestConfig config = RequestConfig.custom().setConnectTimeout(timeOut) //连接超时时间 .setConnectionRequestTimeout(timeOut) //从连接池中取的连接的最长时间 .setSocketTimeout(timeOut) //数据传输的超时时间 .setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用 .build(); httpGet.setConfig(config); //设置请求头 if (!ObjectUtils.isEmpty(heads)) { for (String key : heads.keySet()) { httpGet.addHeader(key,heads.get(key).toString()); } } // 执行请求 response = httpClient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), StringUtils.isEmpty(encoding)?REQUEST_ENCODING:encoding); } } catch (IOException | URISyntaxException e) { e.printStackTrace(); log.info("接口请求解析异常"); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static Object sendPost(String url, String encoding, Map<String,Object> params,Map<String,Object> heads,int timeOut){ //创建httpClient对象 CloseableHttpClient httpClient= HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建http post请求 HttpPost httpPost = new HttpPost(url); //设置请求超时时间 RequestConfig config = RequestConfig.custom().setConnectTimeout(timeOut) //连接超时时间 .setConnectionRequestTimeout(timeOut) //从连接池中取的连接的最长时间 .setSocketTimeout(timeOut) //数据传输的超时时间 .setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用 .build(); httpPost.setConfig(config); if (!ObjectUtils.isEmpty(params)) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : params.keySet()) { paramList.add(new BasicNameValuePair(key, params.get(key).toString())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,StringUtils.isEmpty(encoding)?REQUEST_ENCODING:encoding); httpPost.setEntity(entity); } //设置请求头 if (!ObjectUtils.isEmpty(heads)) { for (String key : heads.keySet()) { httpPost.addHeader(key,heads.get(key).toString()); } } // 执行请求 response = httpClient.execute(httpPost); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(),StringUtils.isEmpty(encoding)?REQUEST_ENCODING:encoding); } }catch (IOException e){ e.printStackTrace(); log.info("接口请求解析异常"); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } }