I want to send POST request (like html form) and get file (HTTP header: "Content-Disposition: attachment; filename="myfile.pdf"). Can you help me?
Asked
Active
Viewed 1.8k times
5
-
Are you sure you mean Java and not Javascript? – Mikhail Mar 01 '11 at 19:47
-
Question too vague. Please describe your environment. Is it a browser-based application? Are you having problems with the Servlet? – rahulmohan Mar 01 '11 at 19:57
2 Answers
11
Your best option is probably to use a third party library such as HttpClient or HTMLUnit.
If you prefer to do it with the standard API it's not that complicated.
// 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();

aioobe
- 413,195
- 112
- 811
- 826
6
Check out HttpClient. There's a pretty comprehensive tutorial here.

Brian Agnew
- 268,207
- 37
- 334
- 440