/**
* <p>Description: post方式请求接口
* @param url 请求路径
* @param HeadParams http头参数
* @param data 数据报文
*/
public static String sendJsonPost(String url, Map<String, String> HeadParams, Object data) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
// Post请求的url
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
//hcy 2021-7-3 09:56:07
connection.setConnectTimeout(50000);
connection.setReadTimeout(50000);
//-------
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
// 获取请求头Map
SapUtils http = new SapUtils();
http.initailizeHeadMap();
if (null != HeadParams && !HeadParams.isEmpty()) {
http.headMap.putAll(HeadParams);
}
// 设置通用的请求属性
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
for (Map.Entry<String, String> entry : (http.headMap).entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
// 建立实际的连接
connection.connect();
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(
connection.getOutputStream(),"UTF-8"));
// 发送请求参数
out.print(data);
// flush输出流的缓冲
out.flush();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送POST请求出现异常!\r\n" + e);
result = e.toString();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e2) {
log.error(e2);
}
}
return result;
}
/**
* 初始化http请求头
*/
public void initailizeHeadMap() {
headMap = new HashMap<String, String>();
headMap.put("accept", "*/*");
headMap.put("connection", "Keep-Alive");
headMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
}