POST to URL and read response

From: Andrew Arace (andrewrarace_at_hotmail.com)
Date: 12/31/03


Date: 31 Dec 2003 11:09:46 -0800

I wrote this, it may be helpful.
It posts data to a URL (same as POST type HTML form) and reads the
response to a String.

Useful for posting data to CGI or other URL based applications.

    /**
     * Writes *requestData* to url *targetURL* as form-data
     * This is the same as pressing submit on a POST type HTML form
     * Throws:
     * MalformedURLException for bad URL String
     * IOException when connection can not be made, or error when
     * reading response
     *
     * @param requestData string to POST to the URL.
     * empty for no post data
     * @param targetURL string of url to post to
     * and read response.
     * @return string response from url.
     */
        private String postDataToURL(String requestData,
                                     String targetURL)
                                 throws MalformedURLException, IOException {
                String XMLResponse = "";
                String nextLine;

                // open the connection and prepare it to POST
                URL url = new URL(targetURL);
                URLConnection URLconn = url.openConnection();

                URLconn.setDoOutput(true);
                URLconn.setDoInput(true);
                URLconn.setAllowUserInteraction(false);
                DataOutputStream dataOutStream =
                        new DataOutputStream(URLconn.getOutputStream());

                // Send the data
                dataOutStream.writeBytes(requestData);
                dataOutStream.close();

                // Read the response
                BufferedReader reader =
           new BufferedReader(new
InputStreamReader(URLconn.getInputStream()));

                while((nextLine = reader.readLine()) != null) {
                        XMLResponse += nextLine;
                }
                reader.close();
                
                return XMLResponse;
        }