importcom.alibaba.fastjson.JSONObject;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.httpclient.HttpStatus;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importjava.io.IOException;/*** @program: myt
* @description
*@author: wlv1314
* @create: 2020-11-22 16:57
**/@Slf4jpublic classHttpClientUtil {private static RequestConfig requestConfig=null;static{
requestConfig= RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(3000).build();
}/*** post请求传输json参数
*@paramurl url地址
*@paramjsonParam 参数
*@return
*/
public staticJSONObject httpPost(String url, JSONObject jsonParam){//post请求返回结果
CloseableHttpClient httpClient =HttpClients.createDefault();
JSONObject jsonResult= null;
HttpPost httpPost= newHttpPost(url);//设置请求和传输超时时间
httpPost.setConfig(requestConfig);try{if (null !=jsonParam){//解决中文乱码问题
//转为服务端编码格式
StringEntity entity = new StringEntity(jsonParam.toString(), "GBK");
entity.setContentEncoding("GBK");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result=httpClient.execute(httpPost);//请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() ==HttpStatus.SC_OK){
String str= "";try{//读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");//把json字符串转换成json对象
jsonResult =JSONObject.parseObject(str);
}catch(Exception e){
log.error("post请求提交失败:" +url, e);
}
}
}catch(IOException e){
log.error("post请求提交失败:" +url, e);
}finally{
httpPost.releaseConnection();
}returnjsonResult;
}
}