package com.farriver.bwf.common.utilities; import com.alibaba.fastjson2.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.Charset; /** * httpclient util 处理http请求工具类 * * @author administrator */ public class HttpClientUtil { private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); private final CloseableHttpClient httpClient; private final RequestConfig requestConfig; public HttpClientUtil(CloseableHttpClient httpClient, RequestConfig requestConfig) { this.httpClient = httpClient; this.requestConfig = requestConfig; } /** * 处理post请求 * * @param jsonObj * @param url * @return * @throws IOException * @throws ClientProtocolException */ private HttpResponse doPost(JSONObject jsonObj, StringBuffer url) throws IOException, ClientProtocolException { HttpResponse response; HttpPost httpPost = new HttpPost(url.toString()); httpPost.setConfig(this.requestConfig); // 构建消息实体 if (jsonObj != null) { StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); // 发送Json格式的数据请求 entity.setContentType("application/json"); httpPost.setEntity(entity); } // do post try { response = httpClient.execute(httpPost); } finally { httpPost.releaseConnection(); } return response; } /** * 处理get请求 * * @param url * @return * @throws IOException * @throws ClientProtocolException */ private HttpResponse doGet(StringBuffer url) throws IOException, ClientProtocolException { HttpResponse response; HttpGet httpGet = new HttpGet(url.toString()); httpGet.setConfig(this.requestConfig); // do get try { response = httpClient.execute(httpGet); } finally { httpGet.releaseConnection(); } return response; } }