废话不多说直接上代码:
private static String postMethod(String urlStr, String data, String postType, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
StringBuffer result = new StringBuffer();
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-type", postType);
conn.setRequestMethod("POST");
conn.setConnectTimeout(connTimeout);
conn.setReadTimeout(readTimeout);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.toString().getBytes(charset));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
return result.toString();
}
public static void main(String[] args) {
//data.toJSONString() 要发送的数据
//application/json 发送数据的类型
// /service/query 方法名
String resultStr = "";
resultStr = postMethod("http://127.0.0.1:8080//service/query", data.toJSONString(), "application/json", "UTF-8", 3000, 3000);
}