StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(add_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); //需要输出
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "UTF-8");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.writeBytes(data);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbf.append(lines);
}
reader.close();
// 断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return sbf.toString();
}
本文介绍了一个使用Java实现HTTP POST请求的方法。通过 HttpURLConnection 进行网络通信,并设置必要的参数如 Content-Type 和 Charset。此外,还展示了如何发送数据并读取服务器响应。

被折叠的 条评论
为什么被折叠?



