我们当然可以考虑使用apache httpcomponent组件, 不过我们也可以使用如下代码:
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
更多的例子可以参考如下网页:
http://www.aviransplace.com/2008/01/08/make-http-post-or-get-request-from-java/
本文提供了一个使用Java进行HTTP POST请求的示例代码。通过构造数据并发送到指定URL,展示了如何设置连接属性、写入数据及读取响应。此外,还提供了一个链接以获取更多示例。
784

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



