HOWTO设置JAX-WS客户机使用ISO-8859-1,而不是UTF-8的?(Howto setu

2019-08-02 06:46发布

我想我的配置JAX-WS客户端在ISO-8859-1发送消息。 目前使用UTF-8。

下面是客户端尝试做的事:

Map<String, Object> reqContext = ((BindingProvider) service).getRequestContext();
Map httpHeaders = new HashMap();
httpHeaders.put("Content-type",Collections.singletonList("text/xml;charset=ISO-8859-1"));
reqContext.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);

但这种设置被忽略,TCPMON显示,以下是由服务器接收:

POST /service/helloWorld?WSDL HTTP/1.1
Content-type: text/xml;charset="utf-8"
Soapaction: "helloWorld"
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
User-Agent: Oracle JAX-WS 2.1.5
Host: 1.1.1.1:8001
Connection: keep-alive
Content-Length: 4135

<?xml version='1.0' encoding='UTF-8'?>
<S:Envelopexmlns:S="http://schemas.xmlsoap.org/soap/envelope/">...  

因此,设置重写和UTF-8被使用,无论是在HTTP报头和XML消息中。 该服务由在UTF-8编码的WSDL中定义。

问:我应该重新定义服务的WSDL在ISO-8899-1进行编码,然后重新生成客户端? 或者,是不是,我只是没有正确设置HTTP头?

Answer 1:

使用处理程序:

public class MyMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outbound.booleanValue()) {
        try {
            context.getMessage().setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
                            "ISO-8859-1");
        }
        catch (SOAPException e) {
            throw new RuntimeException(e);
        }
    }
    return true;
}

并注册处理程序:

    BindingProvider bindProv = (BindingProvider) service;
    List<Handler> handlerChain = bindProv.getBinding().getHandlerChain();
    handlerChain.add(new MyMessageHandler ());


Answer 2:

从jaypi答案似乎是正确的。 但我需要添加一些默认实现。 此外,它很容易把内联:

更新:我猜你必须明确地设置HandlerChain的。 改变getHandlerChain的结果不会做任何事情。

    List<Handler> chain = bindingProvider.getBinding().getHandlerChain();
    chain.add(new SOAPHandler<SOAPMessageContext>() {
      @Override
      public boolean handleMessage(SOAPMessageContext context) {
        LOG.info("BaseService.handleMessage" + context);
        Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outbound.booleanValue()) {
          try {
            context.getMessage().setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "ISO-8859-1");
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
        return true;        
      }

      @Override
      public boolean handleFault(SOAPMessageContext context) {
        return true;
      }

      @Override
      public void close(MessageContext context) {
      }

      @Override
      public Set<QName> getHeaders() {
        return null;
      }      
    });
    bindingProvider.getBinding().setHandlerChain(chain);


文章来源: Howto setup JAX-WS client to use ISO-8859-1 instead of UTF-8?