java使用http发送post请求
/**
* 发送POST方法的请求
* http
* @param url 发送请求的 URL
* @param param 请求参数是 name1=value1&name2=value2 的形式。
* @return 响应结果
*/
public static Object sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
connection.setDoOutput(true);
connection.setDoInput(true);
out = new PrintWriter(connection.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
赠人玫瑰,手有余香~
如果以上对您有帮助,请关注以下微信公众号和小程序,感谢支持!