1 posts in topic
Flat View  Flat View

Posted By:   Elena_Santander
Posted On:   Friday, September 27, 2002 03:42 AM

I have to iniciate a comunication HTTP from my machine to another machive, but I ca┬┤nt an PI to make this..
Where I can find a HTTP API to send and recive?.

Regards, E.

Re: API HTTP send

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.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.

// 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;
cat.debug("Response received: " + resp.toString());
// Disconnect the connection

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

About | Sitemap | Contact