更改(或设置)编码Web服务

时间:2016-04-10 10:00:07

标签: java web-services jax-ws

我有一个使用JAX-WS API(肥皂网服务)的Web服务。

import javax.jws.WebService;

@WebService
public class Accounts {
    public String getFullName(String userID){
        AccountManager GFN = new AccountManager();
        return GFN.getFullName(userID);
    }

如何将其编码更改为“UTF-8”(非英语字符)? 我有点像“@Produces(”text / html; charset = UTF-8“)”但它适用于JAX-RS(宁静的Web服务)我需要JAX-WS的东西。 感谢。

1 个答案:

答案 0 :(得分:1)

首先,您需要尽早获取SOAP消息。最好的起点是javax.xml.ws.handler.LogicalHandler(与更常见的处理程序类型SOAPHandler相对)。

LogicalHandlerSOAPHandler之前拦截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;
   }