Java – how to send a post request and get a file response?
•
Java
I want to send post requests (such as HTML forms) and get files (HTTP Title: "content disposition: attachment; filename =" myfile. PDF "). Can you help me?
Solution
Your best choice may be to use a third-party library, such as httpclient or htmlunit
If you prefer to use standard APIs, it's less 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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码