如何使用apache cxf获取http请求(soap)的有效负载。使用拦截器时缺少信封封闭

时间:2014-07-10 10:04:02

标签: java spring apache cxf interceptor

我试图将自定义标头附加到cxf消息中,它可以工作,但我在消息有效负载方面存在一些问题。

public HttpHeaderInterceptor() {
    super(Phase.USER_PROTOCOL);
}

public void handleMessage(Message message) throws Fault {

    try {

        Map<String, List<String>> headers = (HashMap<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);

        if(validationFlag){

        headerInfo = new ArrayList<String>();
        String messageContent="empty";
        OutputStream os = message.getContent(OutputStream.class);
        StringBuilder responsePayload = new StringBuilder();
        CachedOutputStream cos = (CachedOutputStream) os;
        try {
            cos.writeCacheTo(responsePayload);
            messageContent = IOUtils.toString(cos.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


            //here im getting hashCode of message payload and add to header
            byte[] messageByte = messageContent.getBytes("UTF-8");
            byte[] doFinal = mac.doFinal(messageByte);
            StringBuilder sb = new StringBuilder();
            sb.append(" Checksum:");
            sb.append(Hex.encodeHex(doFinal));

            headerInfo.add(scValidationCode);
            headerInfo.add(sb.toString());
            headers.put("Warning", headerInfo);
        }

    } catch ( Exception e) {
        throw new Fault(e);
    }
}

在这个片段中:

messageContent = IOUtils.toString(cos.getInputStream());
例如,

messageContent是相同的:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:someNamespace xmlns:ns2="http://something.com>some Soap request body</ns2:someNamespace>

但是原始的完整请求有效负载是相等的:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:someNamespace xmlns:ns2="http://something.com>some Soap request body</ns2:someNamespace></soap:Body></soap:Envelope>

所以在我的留言内容我迷路了</soap:Body></soap:Envelope>。 我已经尝试更改org.apache.cxf.phase阶段,但仍然是来自Message的有效负载没有肥皂封套。

我不知道为什么当我试图获取message.getContent(OutputStream.class)时,我只会松开肥皂。 其他任何事情都很好。 HTTP标头正在追加新值。

1 个答案:

答案 0 :(得分:2)

好的,我已经通过几乎所有的cxf链,我​​找到了解决方案。

肥皂信封和身体封闭,正在添加肥皂SoapOutInterceptor,但在子类中正好在ENDING链的SoapOutEndingInterceptor中。

因此,如果你想要有肥皂封闭的完整有效载荷,你必须以两种方式放置你的自定义拦截器:

super(Phase.PRE_STREAM_ENDING);
addBefore(StaxOutInterceptor.StaxOutEndingInterceptor.class.getName());

或第二种方式:

super(Phase.WRITE_ENDING);
addAfter(SoapOutInterceptor.SoapOutEndingInterceptor.class.getName());

玩得开心!