public static JSONObject SmsPost(String url, Map<String, Object> map) {
try {
//创建一个获取连接客户端的工具
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建Post请求
HttpPost httpPost = new HttpPost(url);
//添加请求头
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
//封装请求参数,将map集合转换成json格式
JSONObject jsonString = new JSONObject(map);
//使用StringEntity转换成实体类型
StringEntity entity = new StringEntity(jsonString.toString());
System.out.println(jsonString.toJSONString());
// entity.setContentEncoding("UTF-8");
// entity.setContentType("application/json");//发送json数据需要设置contentType
//将封装的参数添加到Post请求中
httpPost.setEntity(entity);
//执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取响应的实体
HttpEntity responseEntity = response.getEntity();
//转化成字符串
String entityString = EntityUtils.toString(responseEntity);
//转换成JSON格式输出
JSONObject result = JSONObject.parseObject(entityString);
//返回的是Utf-8格式,所以需要转换一下格式,不然乱码
String httpResult = result.get("msg").toString();
result.put("msg", httpResult);
response.close();
httpClient.close();
return result;
} catch (Exception e) {
return null;
}
}
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>