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);
}
}
}