How to use RESTEasy client framework to send data in a POST

David Escandell picture David Escandell · May 20, 2010 · Viewed 33.9k times · Source

I am using the RESTEasy client framework to call a RESTful webservice. The call is made via a POST and sends some XML data to the server. How do I accomplish this?

What is the magical incantation of annotations to use to make this happen?

Answer

Charles Akalugwu picture Charles Akalugwu · Jun 1, 2010

I think David is referring to the RESTeasy "Client Framework". Therefore, your answer (Riduidel) is not particularly what he is looking for. Your solution uses HttpUrlConnection as the http client. Using the resteasy client instead of HttpUrlConnection or DefaultHttpClient is beneficial because resteasy client is JAX-RS aware. To use the RESTeasy client, you construct org.jboss.resteasy.client.ClientRequest objects and build up requests using its constructors and methods. Below is how I'd implement David's question using the client framework from RESTeasy.

ClientRequest request = new ClientRequest("http://url/resource/{id}");

StringBuilder sb = new StringBuilder();
sb.append("<user id=\"0\">");
sb.append("   <username>Test User</username>");
sb.append("   <email>[email protected]</email>");
sb.append("</user>");


String xmltext = sb.toString();

request.accept("application/xml").pathParameter("id", 1).body( MediaType.APPLICATION_XML, xmltext);

String response = request.postTarget( String.class); //get response and automatically unmarshall to a string.

//or

ClientResponse<String> response = request.post();

Hope this helps, Charlie