Thursday, 28 May 2009

Java 'PUT' for RESTful service

I was looking around for a Java example of 'PUT' for  the CherryPy/COOL server, and at least came across a 'GET' at Jose Sandovals blog... but not much on the other methods. Andrea Formica (Atlas Muons) is trying to use it to upload calibrations. Here's the solution he came up with, using Apache's library:

public String coolPutCherryPyHttpClient() throws IOException, FileNotFoundException{
String res = "none";
HttpClient client = new HttpClient();
PutMethod put = new PutMethod(this.writenodeUrl);
    try {
String payloaddata = " 999999. "
"";
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(this.namethis.psswd);
client.getState().setCredentials(new AuthScope(serverUrl, portNumber, AuthScope.ANY_REALM), defaultcreds);

NameValuePair par = new NameValuePair();
par.setName("payload");
par.setValue(payloaddata);
NameValuePair[] params = new NameValuePair[1];
params[0] = par;
put.setQueryString(params);


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

        if (statusCode != HttpStatus.SC_OK) {
          System.err.println("Method failed: " + put.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = put.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        res = new String(responseBody);
        System.out.println(new String(responseBody));

      } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
      } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
      } finally {
        // Release the connection.
        put.releaseConnection();
      }  
return res;
}

No comments: