我正在使用
调用SOAP webserive我正面临WebService请求调用的问题,其中请求字符串(XML)在发送时被格式化。
预期请求:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:serviceRequest xmlns:ns2="urn:example.com/xml/schemas/v1_0/">
<referenceNum>5361610270000002</referenceNum>
<client>ABCD</client>
<serviceName>GET.PERSONAL.DETAIL</serviceName>
<UserId>USER_1234</UserId>
<data><![CDATA[<ns2:getDetailRequest xmlns:ns2="urn:example.com/xml/schemas/v1_0/">
<HEADER>
<serviceName>GET.PERSONAL.DETAIL</serviceName>
<serviceType>SYNC</serviceType>
<serviceVersion>1.0</serviceVersion>
</HEADER>
</ns2:getAccountDetailRequest>]]>
</data>
</ns2:serviceRequest>
</soap:Body>
</soap:Envelope>
发送实际请求:
{{1}}
我正在使用Apache CXF(SOAP)进行webservice调用。 Java Object的封送处理由CXF和JAXB库内部处理。
是否有人遇到过&lt; [CDATA []]&gt;内部元素的问题?在封送期间如何格式化或如何解决这个问题?
答案 0 :(得分:0)
我使用拦截器找到了解决方案。
public class CustomSoapCxfInterceptor extends AbstractSoapInterceptor {
public CustomSoapCxfInterceptor() {
super(Phase.PRE_STREAM);
getAfter().add(AttachmentOutInterceptor.class.getName());
}
@Override
public void handleMessage(SoapMessage message) {
try {
message.put("disable.outputstream.optimization", Boolean.TRUE);
XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(message.getContent(OutputStream.class));
CDataXMLStreamWriter cDataXMLStreamWriter = new CDataXMLStreamWriter(writer);
message.setContent(XMLStreamWriter.class, cDataXMLStreamWriter);
} catch (Exception exception) {
DefaultLogger.error(exception);
}
}
}
CDataXMLStreamWriter扩展了DelegatingXMLStreamWriter
public class CDataXMLStreamWriter extends DelegatingXMLStreamWriter {
private int counter = 1;
private String currentElementName;
public CDataXMLStreamWriter(XMLStreamWriter del) {
super(del);
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
boolean useCData = checkIfCDATAneededForCurrentElement();
if (useCData) {
super.writeCData(text);
} else {
super.writeCharacters(text);
}
}
private boolean checkIfCDATAneededForCurrentElement() {
if ("data".equals(currentElementName))
return true;
return false;
}
public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
currentElementName = local;
super.writeStartElement(prefix, local, uri);
}
@Override
public void writeEndElement() throws XMLStreamException {
if ("data".equals(currentElementName)) {
if (this.counter == 1) {
super.writeEndElement();
}
this.counter++;
} else {
super.writeEndElement();
}
}
}