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.


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


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

public void writeRequest(OutputStream outputStream) throws IOException {
PrintWriter pr = new PrintWriter(outputStream);

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

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


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

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

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

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.

return false;

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

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


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s