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?
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?
I borrowed from this example : Build restful service with RESTEasy the following code fragment, which seems to do exactly what you want, no ?
URL url = new URL("http://localhost:8081/user");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
StringBuffer sbuffer = new StringBuffer();
sbuffer.append("<user id=\"0\">");
sbuffer.append(" <username>Test User</username>");
sbuffer.append(" <email>[email protected]</email>");
sbuffer.append("</user>");
OutputStream os = connection.getOutputStream();
os.write(sbuffer.toString().getBytes());
os.flush();
assertEquals(HttpURLConnection.HTTP_CREATED, connection.getResponseCode());
connection.disconnect();
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