How To Modify The Raw XML message of an Outbound CXF Request?

前端 未结 6 631
滥情空心
滥情空心 2020-11-27 17:07

I would like to modify an outgoing SOAP Request. I would like to remove 2 xml nodes from the Envelope\'s body. I managed to set up an Interceptor and get the generated Stri

6条回答
  •  自闭症患者
    2020-11-27 17:53

    this one's working for me. It's based on StreamInterceptor class from configuration_interceptor example in Apache CXF samples.

    It's in Scala instead of Java but the conversion is straightforward.

    I tried to add comments to explain what's happening (as far as I understand).

    import java.io.OutputStream
    
    import org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor
    import org.apache.cxf.helpers.IOUtils
    import org.apache.cxf.io.CachedOutputStream
    import org.apache.cxf.message.Message
    import org.apache.cxf.phase.AbstractPhaseInterceptor
    import org.apache.cxf.phase.Phase
    
    // java note: base constructor call is hidden at the end of class declaration
    class StreamInterceptor() extends AbstractPhaseInterceptor[Message](Phase.PRE_STREAM) {
    
      // java note: put this into the constructor after calling super(Phase.PRE_STREAM);
      addBefore(classOf[SoapPreProtocolOutInterceptor].getName)
    
      override def handleMessage(message: Message) = {
        // get original output stream
        val osOrig = message.getContent(classOf[OutputStream])
        // our output stream
        val osNew = new CachedOutputStream
        // replace it with ours
        message.setContent(classOf[OutputStream], osNew)
        // fills the osNew instead of osOrig
        message.getInterceptorChain.doIntercept(message)
        // flush before getting content
        osNew.flush()
        // get filled content
        val content = IOUtils.toString(osNew.getInputStream, "UTF-8")
        // we got the content, we may close our output stream now
        osNew.close()
        // modified content
        val modifiedContent = content.replace("a-string", "another-string")
        // fill original output stream
        osOrig.write(modifiedContent.getBytes("UTF-8"))
        // flush before set
        osOrig.flush()
        // replace with original output stream filled with our modified content
        message.setContent(classOf[OutputStream], osOrig)
      }
    }
    
    

提交回复
热议问题