POST to URL and read response

A

Andrew Arace

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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top