java post请求
public String post(String urlStr, JSONObject data, Map<String, String> properties) {
try {
log.info("请求url={}", urlStr);
log.info("请求体数据data={}", data.toJSONString());
log.info("请求头参数properties={}", properties);
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (String key : properties.keySet()) {
connection.setRequestProperty(key, properties.get(key));
}
PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
pw.write(data.toJSONString());
pw.flush();
pw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
connection.disconnect();
return result.toString();
} catch (Exception e) {
log.error("post请求失败");
return "post请求失败!";
}
}