Wednesday, December 18, 2013

[Code Snippet] Calling a REST operation protected with OAuth via HTTPClient


private void callRest(HttpServletRequest request, HttpServletResponse response) throws IOException {
 
 PostMethod post = new PostMethod("http://localhost:9764/jaxrs_basic/services/customers/customerservice/customers/name");
 
 post.addRequestHeader("Accept", "text/plain");
 post.addRequestHeader("Authorization", "Bearer " + oauthToken);
 
 try {
  RequestEntity myEntity = new StringRequestEntity("", "text/plain", "ISO-8859-1");
  post.setRequestEntity(myEntity);
  
  HttpClient httpclient = new HttpClient();
  int result = httpclient.executeMethod(post);
  
  System.out.println("Response status code: " + result);
  System.out.println("Response body: ");
  System.out.println(post.getResponseBodyAsString());
  
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  post.releaseConnection();
 }
}

No comments: