How to send a POST request and get a file response?

I want to send a POST request (for example, an html form) and get a file (HTTP header: "Content-Disposition: attachment; filename =" myfile.pdf "). Can you help me?

+5
source share
2 answers

It is best to use a third-party library such as HttpClient or HTMLUnit .

If you prefer to do this with the standard API, this is not so difficult.

// 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();
+11
source

Check the HttpClient box . Here is a pretty complete tutorial here .

+6

All Articles