I have used the following java code to POST xml data to a remote url and get the response. Here, I am using an xml file as the input. What I need is to pass the xml as a string
The setRequestEntity method on org.apache.commons.httpclient.methods.PostMethod has an overloaded version that accepts StringRequestEntity as argument. You should use this if you wish to pass in your data as a string (as opposed to an input stream). So your code would look something like this:
String xml = "whatever.your.xml.is.here";
PostMethod post = new PostMethod(strURL);
try {
StringRequestEntity requestEntity = new StringRequestEntity(xml);
post.setRequestEntity(requestEntity);
....
Hope that helps.
You can convert the XML to String from this method
public String convertXMLFileToString(String fileName)
{
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
Add you can pass this string as a parameter on PostMethod
like this.
PostMethod post = new PostMethod(strURL);
post.addParamter("paramName", convertXMLFileToString(strXMLFilename ) );
The whole XML will be transmitted to the client in a queryString
.
To get your XML file contents as a String use (add catch-block for IOException)
StringBuilder bld = new StringBuilder();
FileReader fileReader = new FileReader(input);
BufferedReader reader = new BufferedReader(fileReader);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
bld.append(line);
}
String xml = bld.toString();
The better way is to use Java Web Services JAX-WS or Java Restful Web Services JAX-RS.