java 发送POST请求方法
废话不说,直接贴代码,试用于调用第三方平台接口使用~
public Map test(HttpServletRequest request) {
//定义发送数据
JSONObject param = new JSONObject();
param.put("khmc", "张三");
param.put("tel", "13333333");
//定义接收数据
JSONObject result = new JSONObject();
String url = "http://www.baidu.com";
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
result.put("error", "连接错误!");
}
System.out.println(result);
return result;
}