Saturday, 3 January 2015

How to POST xml data through RestTemplate?



I am using RestTemplate to execute an URL. The url takes an input parameter which is in XML format.


I have a XML like below which is stored as a String in xmlData variable and I need to pass this String to my url in client_data variable -



<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://www.google.com model.xsd"
xmlns="http://www.google.com">
<client id="100">
<clock>
<for>
<etc>val(tery) = 1</etc>
<while><![CDATA[val(tery) < 20]]></while>
</for>
</clock>
</model>
</ClientData>


Below is the code I have -



String xmlData = getXMLData(); // this will return me above XML data as it is in String format
String url = generateURL(xmlData);

// but this line is throwing exception and returning Bad Request
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);


Below is how my url String looks like and RestTemplate internally does the URL encoding as per my understanding then why I am still seeing exception being thrown? I am thinking, I am not using RestTemplate properly I guess.



http://localhost:8080/test_tmp?client_data=<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://www.google.com model.xsd"
xmlns="http://www.google.com">
<client id="100">
<clock>
<for>
<etc>val(tery) = 1</etc>
<while><![CDATA[val(tery) < 20]]></while>
</for>
</clock>
</model>
</ClientData>


If I url encode the XML string manually and hit the url through the browser then it works fine. What wrong I am doing here? Do I need to remove line breaks in my xmlData variable?


Also as of now, I am using GET to do this but in general, I should be sending my XML data as POST since my XML can grow bigger and URI has a limit. Can anyone provide an example how would I post an XML data through RestTemplate?


No comments:

Post a Comment