Using Java’s HttpClient to send a PUT

After a lot of searching the net, I wrote this method a few weeks back to write a string (or file) to a web server using Java’s HttpClient. It seemed ridiculous that I couldn’t find an example to cut and paste. So here it is for the next person.

Cheers.


public boolean store (final String file) {
HttpClient client = new HttpClient();
PutMethod method = new PutMethod("http://localhost:80");

method.setPath("/path");

try {
RequestEntity re = new RequestEntity() {
@Override
public boolean isRepeatable() {
return false;
}

@Override
public void writeRequest(OutputStream outputStream) throws IOException {
PrintWriter pr = new PrintWriter(outputStream);
pr.println(file);
pr.flush();
}

@Override
public long getContentLength() {
return source.getBytes().length;
}

@Override
public String getContentType() {
return "application/json";
}
};

method.setRequestEntity(re);

//Execute the method
int statusCode = client.executeMethod(method);

switch(statusCode) {
case HttpStatus.SC_CREATED:
return true;

default:
log.error("Unhandeled result code {}", statusCode);
log.error(new String(method.getResponseBody()));
break;
}

return false;
} catch (HttpException ex) {
log.error("Fatal protocol violation: {}", ex.getMessage());
log.error(ex.getMessage(), ex);
} catch (IOException ex) {
log.error("Fatal transport error: {}", ex.getMessage());
log.error(ex.getMessage(), ex);
} finally {
// Release the connection.
method.releaseConnection();
}

return false;
}

This entry was posted in internet, programming and tagged , . Bookmark the permalink.

One Response to Using Java’s HttpClient to send a PUT

  1. Brian says:

    Thanks! I had a question about creating a PUT with HttpClient and this example answered it.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s