import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import org.apache.commons.httpclient.HttpStatus;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;import java.io.IOException;/** * @program: myt * @description * @author: wlv1314 * @create: 2020-11-22 16:57 **/@Slf4jpublic class HttpClientUtil { private static RequestConfig requestConfig=null; static { requestConfig = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(3000).build(); } /** * post请求传输json参数 * @param url url地址 * @param jsonParam 参数 * @return */ public static JSONObject httpPost(String url, JSONObject jsonParam){ // post请求返回结果 CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(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(); } return jsonResult; }}
运行时报错:
java.lang.ClassNotFoundException:org.apache.http.config.Lookup
解决办法:
大家在调用http接口是 需要的jar包是httpclient-4.5.jar,但是还需要httpcore-4.4.1.jar
加入httpcore依赖即可。
原文转载:http://www.shaoqun.com/a/493180.html
塔图:https://www.ikjzd.com/w/2274
一淘网比价平台:https://www.ikjzd.com/w/1698
打折网:https://www.ikjzd.com/w/74
importcom.alibaba.fastjson.JSONObject;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.httpclient.HttpStatus;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.meth
pat:pat
c2c模式:c2c模式
龙岗长途汽车站咨询电话是多少?:龙岗长途汽车站咨询电话是多少?
第一次泡温泉需要带什么装备吗?:第一次泡温泉需要带什么装备吗?
暑假去海南五指山漂流需要注意什么事项啊?:暑假去海南五指山漂流需要注意什么事项啊?
No comments:
Post a Comment