Using Java’s HttpClient to send a PUT
Jan 15th 2012Joeinternet,
programming
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;
}
