11

我想将我的 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/">...  

因此,该设置被覆盖并在 HTTP 标头和 XML 消息中使用 UTF-8。该服务由以 UTF-8 编码的 WSDL 定义。

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

4

2 回答 2

9

使用处理程序:

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 ());
于 2014-07-31T10:02:38.420 回答
3

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);
于 2016-11-22T02:16:35.433 回答