本来网上有很多HttpUtil工具类封装,里面封装了各种doget/dopost文章来源:https://www.toymoban.com/news/detail-517654.html
本身自己项目之前也有人用过,但是最近对接一个第三方短信平台,按照他们的文档需要传参头部参数,但是不知道为什么用现有的post请求没法修改头部参数,所以自己写一个post请求吧文章来源地址https://www.toymoban.com/news/detail-517654.html
//短信平台要求固定的头部参数格式
Map<String, String> header = Maps.newHashMap();
header.put("Accept", "application/json;charset=utf-8");
header.put("Content-Type", "application/json;charset=utf-8");
//请求参数的账号密码以及加密
LinkedHashMap map = new LinkedHashMap();
map.put("userName", name);
String result = HttpUtil.doPostJson("url", header, JsonHelper.objectToJson(map));
public static String doPostJson(String url,Map<String, String> headerMap, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator(); //循环增加header
while(headerIterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
httpPost.addHeader(elem.getKey(),elem.getValue());
}
}
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
到了这里,关于记录一下用httpUtil工具类的post请求带头部参数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!