httpf发送 json_HttpClient 发送JSON和发送普通参数

HttpClient 版本4.4

1:发送JSON

/**

* 发送post请求(发送JSON)

* @param jsonStr

* @param serverUrl

* @return Map

*/

public String httpPost(String jsonStr, String serverUrl) {

CloseableHttpClient httpclient = HttpClients.createDefault();

CloseableHttpResponse httpresponse = null;

String httpresponseText = null;

HttpPost httpPost = new HttpPost(serverUrl);

try {

httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));

logger.info("正在向:[" + serverUrl + "] 发送请求");

httpresponse = httpclient.execute(httpPost, new HttpClientContext());

HttpEntity httpEntity = httpresponse.getEntity();

httpresponseText = EntityUtils.toString(httpEntity, "UTF-8");

if(StrKit.isBlank(httpresponseText)){

logger.error("请求响应数据为空,httpresponseText:" + httpresponseText);

throw new UFBusinessException("请求数据失败,请重试");

}

logger.info("请求响应数据,httpresponseText:" + httpresponseText);

return httpresponseText;

} catch (Throwable e) {

logger.error("发送POST请求失败:", e);

throw new UFBusinessException("请求数据失败,请重试");

} finally {

try {

if (httpresponse != null)

httpresponse.close();

if (httpclient != null)

httpclient.close();

} catch (IOException e) {

logger.error("关闭资源失败:", e);

}

}

}

在发送JSON时候用 request.getPara...() 是获取不到值的!

2:发送普通请求

/**

* 发送post请求(非JSON)

* @param jsonStr

* @param serverUrl

* @return Map

*/

public String httpPost(Map params, String serverUrl) {

CloseableHttpClient httpclient = HttpClients.createDefault();

CloseableHttpResponse httpresponse = null;

String httpresponseText = null;

HttpPost httpPost = new HttpPost(serverUrl);

try {

List pairList = new ArrayList();

// 循环参数

for (Map.Entry entry : params.entrySet()) {

pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));

logger.info("正在向:[" + serverUrl + "] 发送请求");

httpresponse = httpclient.execute(httpPost);

HttpEntity httpEntity = httpresponse.getEntity();

httpresponseText = EntityUtils.toString(httpEntity, "UTF-8");

if (StrKit.isBlank(httpresponseText)) {

logger.error("请求响应数据为空,httpresponseText:" + httpresponseText);

throw new UFBusinessException("请求数据失败,请重试");

}

logger.info("请求响应数据,httpresponseText:" + httpresponseText);

return httpresponseText;

} catch (Throwable e) {

logger.error("发送POST请求失败:", e);

throw new UFBusinessException("请求数据失败,请重试");

} finally {

try {

if (httpresponse != null)

httpresponse.close();

if (httpclient != null)

httpclient.close();

} catch (IOException e) {

logger.error("关闭资源失败:", e);

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值