Java工具类--http请求-post
支持各类型报文与参数说明
说明:
- url : 地址
- timeout:超时时间 如3秒 3*1000
- contentType:类型 如
- application/x-www-form-urlencoded
- application/json
- application/xml
- requestBody:报文内容 如
- application/x-www-form-urlencoded时 为 "key=value&key2=value2"
- application/json时 为 " \"key\":\"value\", \"key2\":\"value2\" "
- application/xml时 为 "<?xml version=\"1.0\" encoding=\"utf-8\" ?><request>" + "<head>" + str_head + "</head>" + "<body>" + str_body + "</body>" + "</request>"
- encoding:字符编码 如 utf-8
public static String postJsonBody(String url, int timeout, String contentType, String requestBody, String encoding){HttpPost post = new HttpPost(url);try {post.setHeader("Content-type", contentType);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setExpectContinueEnabled(false).build();post.setConfig(requestConfig);post.setEntity(new StringEntity(requestBody, encoding));logger.info("[HttpUtils Post] begin invoke url:" + url + " , params:" + requestBody);CloseableHttpResponse response = httpclient.execute(post);try {HttpEntity entity = response.getEntity();try {if(entity != null){String str = EntityUtils.toString(entity, encoding);logger.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+str);return str;}} finally {if(entity != null){entity.getContent().close();}}} finally {if(response != null){response.close();}}} catch (UnsupportedEncodingException e) {logger.error("UnsupportedEncodingException", e);} catch (Exception e) {logger.error("Exception", e);} finally {post.releaseConnection();}return "";}