package com.ruoyi.integration.chengdujianguan.util; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * @author 联联充电 */ @Slf4j @SuppressWarnings(value = "unused") public class HttpRequestUtil { /** * httpClient--post请求--http * * @param url * @param json * @return */ public static String httpPost(String url, String json, String token) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { //创建httpPost HttpPost httpPost = new HttpPost(url); //设置Content-Type httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Authorization", token); //写入json数据 httpPost.setEntity(new StringEntity(json)); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(50000) .setConnectionRequestTimeout(50000) .setSocketTimeout(50000) .build(); httpPost.setConfig(requestConfig); //发起请求,获取response对象 response = httpClient.execute(httpPost); //获取结果状态码 int resultCode = response.getStatusLine().getStatusCode(); if (resultCode == 200) { //获取返回数据实体对象 HttpEntity entity = response.getEntity(); //转化为字符串 String result = EntityUtils.toString(entity, "UTF-8"); //封装统一的返回数据接收类 //ResponseMsg responseMsg = (ResponseMsg) JSON.parse(result); return result; } else { log.info("http请求失败"); } } catch (Exception e) { log.info("http请求异常"); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (Exception e) { log.info(e.getMessage(), e); } } return null; } }