1.导入依赖:
|
2.执行POST请求代码方式一:
|
3.执行POST请求方式二:
private Integer post(String url, MocInfo info, MocInfo.Action action) { OutputStream out = null; HttpURLConnection conn = null; int result = -10; String body = null; try { body = JSONObject.toJSONString(info);//把对象转换成JSON格式的字符串 //url=127.0.0.1:8080/app/edit conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(30 * 1000); conn.setReadTimeout(30 * 1000); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.connect(); out = conn.getOutputStream(); out.write(body.getBytes(StandardCharsets.UTF_8)); out.flush(); result = conn.getResponseCode(); } catch (Exception e) { log.error("Post [" + url + "] Err :" + e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } if (out != null) { try { out.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } if (result < 200 || result >= 300) { log.info("Post .. " + url + " : " + body); } return result; } |