I have to make a SOAP POST request as below
POST /sample/demo.asmx HTTP/1.1
Host: www.website.org
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "https://www.website.org/Method"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Method xmlns="https://www.ourvmc.org/">
<item1>string</item1>
<item2>string</item2>
<item3>string</item3>
<item4>string</item4>
</Method>
</soap:Body>
</soap:Envelope>
I have acheived upto
POST /sample/demo.asmx HTTP/1.1
Host: www.website.org
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "https://www.website.org/Method"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Method xmlns="http://tempuri.org/"/>
</soap:Body>
</soap:Envelope>
and I have a POJO class with name Method and getter setter for all the item1, item2, item3, item4. I need to convert that POJO to xml format which is
<item1>string</item1>
<item2>string</item2>
<item3>string</item3>
<item4>string</item4>
and then POST it. can any one suggest how to do it ? I have researched but didn't find any useful solution.
Use below XMLUtil for converting pojo to xml
Usage Example :
1) Assume Pojo is Student
@XmlRootElement(name = "Student")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
@XmlAttribute
private String type;
@XmlElement(name="Name")
private String name;
public void setType(String type) {
this.type = type;
}
public void setName(String name) {
this.name = name;
}
}
2) XMLUtil
import java.io.StringWriter;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class XMLUtil {
public static String toXML(Object data) {
String xml = "";
try {
LOGGER.info("Generating xml for: " + data.getClass());
JAXBContext jaxbContext = JAXBContext.newInstance(data.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//jaxbMarshaller.marshal(data, System.out);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(data, sw);
xml = sw.toString();
} catch (JAXBException e) {
//handle your exception here
}
return xml;
}
}
3) Set data to student object and pass to util
Student st = new Student();
st.setType("schoolStudent");
st.setName("Devendra");
String studentXml = XMLUtil.toXML(st);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With