我必须发出一个SOAP POST请求,如下所示
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>
我已经实现了
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>
我有一个名为Method和getter setter的POJO类,用于所有item1,item2,item3,item4。 我需要将该POJO转换为xml格式
<item1>string</item1>
<item2>string</item2>
<item3>string</item3>
<item4>string</item4>
然后发布它。任何人都可以建议怎么做? 我已经研究过,但没有找到任何有用的解决方案。
答案 0 :(得分:2)
使用以下XMLUtil将pojo转换为xml
用法示例:
1)假设Pojo是学生
@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)将数据设置为student对象并传递给util
Student st = new Student();
st.setType("schoolStudent");
st.setName("Devendra");
String studentXml = XMLUtil.toXML(st);
答案 1 :(得分:0)
考虑使用JAXB:https://jaxb.java.net/2.2.11/docs/ch01.html#documentation
对于实际发布,请考虑Apache CXF:http://cxf.apache.org/docs/index.html
有关使用JAXB + CXF从POJO生成XML的更多信息:http://cxf.apache.org/docs/jaxb.html