开始之前,您需要尽早获得SOAP消息。最好的起点是
javax.xml.ws.handler.LogicalHandler
(与更常见的处理程序类型
SOAPHandler
相对)。
LogicalHandler
在
SOAPHandler
之前拦截SOAP有效载荷,因此这是理想的位置。
在此处理程序中,您可以随心所欲地处理消息,远在编码成问题之前。您的代码应该像这样。
public class YourHandler implements LogicalHandler{
public boolean handleMessage(LogicalMessageContext context) {
boolean inboundProperty= (boolean)context.get(MessageContext.MESSAGE_INBOUND_PROPERTY);
if (inboundProperty) {
LogicalMessage lm = context.getMessage();
Source payload = lm.getPayload();
Source recodedPayload = modifyEncoding(payload);
lm.setPayload(recodedPayload)
}
return true;
}
}
现在你已经有了这条消息。如何处理编码的更改可能会比较棘手,但完全由您决定。
您可以选择在整个消息上设置编码,或者通过导航(使用
xpath)到您感兴趣的字段并仅操作该字段。即使对于这两个选项,也有几种实现方式。我将采用懒惰的方式:在整个有效载荷上设置编码:
private Source modifyEncoding(Source payload){
StringWriter sw = new StringWriter();
StreamSource newSource = null;
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StreamResult output = new StreamResult(sw);
transformer.transform(source, output);
StringReader sReader = new StringReader(sw.toString());
newSource = new StreamSource(sReader);
} catch(Exception e){
ex.printStackTrace();
}
return newSource;
}
在使用了
LogicalHandler
之后,现在你需要使用
SOAPHandler
。在这里,设置编码更加简单,但是它的行为依赖于具体实现。你的
SOAPHandler
可以像这样:
public class YourSOAPHandler implements SOAPHandler{
public boolean handleMessage(SOAPMessageContext msgCtxt){
boolean inbound = (boolean)msgCtxt.get(MessageContext.MESSAGE_INBOUND_PROPERTY);
if (inbound){
SOAPMessage msg = msgCtxt.getMessage();
msg.setProperty(javax.xml.soap.SOAPMessage.CHARACTER_SET_ENCODING,"UTF-8");
msgCtxt.Message(msg);
}
}
return true;
}