我想发送 POST 请求(如 html 表单)并获取文件(HTTP 标头:“Content-Disposition: attachment; filename="myfile.pdf")。你能帮帮我吗?
问问题
17737 次
2 回答
11
您最好的选择可能是使用第三方库,例如HttpClient或HTMLUnit。
如果您更喜欢使用标准 API 来做这件事,那就没那么复杂了。
// 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();
于 2011-03-01T19:48:07.133 回答
6
查看HttpClient。这里有一个非常全面的教程。
于 2011-03-01T19:46:40.530 回答