Java 更改(或设置)编码web服务
我有一个使用JAX-WSAPI(SOAPWeb服务)的web服务 如何将其编码更改为“UTF-8”(非英语字符)? 我找到了类似“@products(“text/html;charset=UTF-8”)”的东西,但它是用于JAX-RS(RESTfulWeb服务)的,我需要用于JAX-WS的东西。Java 更改(或设置)编码web服务,java,web-services,jax-ws,xpath,Java,Web Services,Jax Ws,Xpath,我有一个使用JAX-WSAPI(SOAPWeb服务)的web服务 如何将其编码更改为“UTF-8”(非英语字符)? 我找到了类似“@products(“text/html;charset=UTF-8”)”的东西,但它是用于JAX-RS(RESTfulWeb服务)的,我需要用于JAX-WS的东西。 谢谢。首先,您需要尽早获得SOAP消息。最好的开始位置是(与更常见的处理程序类型相反,) LogicalHandler在SOAPHandler之前拦截SOAP负载,因此它是执行此操作的理想位置 在这个处
谢谢。首先,您需要尽早获得SOAP消息。最好的开始位置是(与更常见的处理程序类型相反,)
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); //This is where you change the encoding. We'll talk more about this
lm.setPayload(recodedPayload) //remember to stuff the payload back in there, otherwise your change will not be registered
}
return true;
}
}
现在你有消息了。如何处理编码的变化可能很棘手,但完全取决于您
您可以选择在整个消息上设置编码,或者导航(使用)到您感兴趣的字段并进行处理。即使是这两种选择,也有几种方法可以同时实现。我将采用惰性路线:在整个有效负载上设置编码:
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"); //this determines the outcome of the transformation
StreamResult output = new StreamResult(sw);
transformer.transform(source, output);
StringReader sReader = new StringReader(sw.toString());
newSource = new StreamSource(sReader);//Stuff the re-encoded xml back in a Source
} 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); //always put the message back where you found it.
}
}
return true;
}
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); //always put the message back where you found it.
}
}
return true;
}