Posted By:
Stephen_McConnell
Posted On:
Friday, September 27, 2002 04:54 AM
Funny you should ask. We just had to do this:
public String postDocument(String doc, URL url) {
HttpURLConnection connection = null;
BufferedReader r = null;
try {
// Get the connection
connection = (HttpURLConnection)url.openConnection();
// Set up the connection parameters.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod( "POST" );
// Get the header properties.
for(Enumeration e = headers.propertyNames(); e.hasMoreElements() ;) {
String propName = (String)e.nextElement();
connection.setRequestProperty( propName, headers.getProperty(propName));
}
// Get an output stream to send the document
OutputStream out = connection.getOutputStream();
Writer wout = new BufferedWriter(new OutputStreamWriter(out));
// Write the document.
wout.write(doc);
wout.flush();
out.close();
// Get the response code from the site you are sending to.
int code = connection.getResponseCode();
// Read the response.
if (code >= HttpURLConnection.HTTP_OK && code < HttpURLConnection.HTTP_MULT_CHOICE) {
// Read the response
BufferedReader backin = new BufferedReader(new InputStreamReader(connection.getInputStream()));
cat.debug("Inspecting the response");
StringBuffer resp = new StringBuffer();
while (true) {
String line = backin.readLine();
if (line == null) break;
resp.append(line);
}
backin.close();
cat.debug("Response received: " + resp.toString());
}
// Disconnect the connection
connection.disconnect();
} catch (IOException e) {
failure = connection.getHeaderField(0);
System.out.println("Unexpected IOExcpetion when trying to POST the data: " + e.getMessage());
System.out.println("POST Failure: " + failure);
//e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
return failure;
}
You will need a couple of methods to add headers to a Properties Object:
Properties headers = new Properties();
public void addHeader(String name, String value) {
headers.setProperty(name, value);
System.out.println("Setting property " + name + ":" + value);
}
You would set up the HTTP headers you need by calling the above method. Then, pass
the document and the URL you want to send it to to the
postDocument() method.
Hope this helps
Stephen McConnell