httpclient 调取接口_HttpClient接口调用-客户端

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值