/**
* 模拟发送HTTP请求
* @author 白鹿
* @param url
* @param paramMap
*/
public static String sendHttp(String url,String str) {
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();//设置请求和传输超时时间
String returnValue="0";
try {
//HttpGet httpPost = new HttpGet(url);
HttpPost httpPost = new HttpPost(url);
StringEntity entity=new StringEntity(str,Charset.forName("UTF-8"));
entity.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
LOG.info("请求地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
LOG.info("----------------------------------------");
// 打印响应状态
LOG.info(response.getStatusLine());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
returnValue=EntityUtils.toString(resEntity,"UTF-8");
}
httpPost.releaseConnection();
response.close();
return returnValue;
} catch (Exception e) {
//e.printStackTrace();
LOG.error("请求失败", e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}
HttpUtils调用
最新推荐文章于 2023-08-18 13:52:36 发布