SNpn
SNpn

Reputation: 2207

Sending a XML file via POST to a RESTful service in Java

I need to send a XML file using POST to a web service. I have a client application that creates a XML file which stores all the information required to send to the web application, but I am not sure how to go about sending it.

My XML looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Comment>
  <Poll_ID>2</Poll_ID>
  <Name>wpoon</Name>
  <Text>asdasdas</Text>
  <Timestamp>2012-10-14T10:30:25</Timestamp>
</Comment>

And the RESTful service I will be sending it to has the URL:

http://localhost:8080/TESTINGrestful/rest/polls/comment

Could anyone advise me how to do this, any help would be appreciated.

Upvotes: 3

Views: 57210

Answers (2)

ILally
ILally

Reputation: 339

Similar to previous approach but with HttpClientBuilder rather than the deprecated DefaultHttpClient. This example also uses the contentType Json.

HttpPost postRequest = new HttpPost( "http://localhost:8080/service_url" );

StringEntity input = new StringEntity("{\"jsonExample\": \"12345\"}");
input.setContentType("application/json");
postRequest.setEntity(input);

HttpResponse response = HttpClientBuilder.create().build().execute(postRequest);

String json = EntityUtils.toString(response.getEntity());

Upvotes: 0

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

There's a good example here from Apache HttpClient:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/TESTINGrestful/rest/polls/comment");
StringEntity input = new StringEntity("<Comment>...</Comment>");
input.setContentType("text/xml");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);

Upvotes: 12

Related Questions