如何从 cxf outInterceptor 获取响应正文



我正在编写一些代码来收集一些控制器的请求参数和响应正文。

由于项目框架是apache CXF,哪个版本是3.1.18

我编写了一个拦截器扩展了抽象相位拦截器以收集阶段Phase.RECEIVE中的参数,这是有效的。

但是当一个写一个outInterceptor扩展AbstractPhaseInterceptor来收集控制器的响应时,我发现我没有办法做到这一点,拦截器中只有一个方法handleMessage(Message message),我无法从消息中获取任何我想要的东西

有人可以帮助我吗?我是CXF的新手。谢谢!

我从另一个斑点中找到了答案

package XXX.web.webservice.interceptor;  
import java.io.ByteArrayInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import org.apache.commons.io.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;  
import org.apache.log4j.Logger;  
public class ArtifactOutInterceptor extends AbstractPhaseInterceptor<Message>{  
private static final Logger log = Logger.getLogger(ArtifactOutInterceptor.class);  
public ArtifactOutInterceptor() {  
//这儿使用pre_stream,意思为在流关闭之前  
super(Phase.PRE_STREAM);  
}  
public void handleMessage(Message message) {  
try {  
OutputStream os = message.getContent(OutputStream.class);  
CachedStream cs = new CachedStream();  
message.setContent(OutputStream.class, cs);  
message.getInterceptorChain().doIntercept(message);  
CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);  
InputStream in = csnew.getInputStream();  
String xml = IOUtils.toString(in);  
//这里对xml做处理,处理完后同理,写回流中  
IOUtils.copy(new ByteArrayInputStream(xml.getBytes()), os);  
cs.close();  
os.flush();  
message.setContent(OutputStream.class, os);  

} catch (Exception e) {  
log.error("Error when split original inputStream. CausedBy : " + "n" + e);  
}  
}  
private class CachedStream extends CachedOutputStream {  
public CachedStream() {  
super();  
}  
protected void doFlush() throws IOException {  
currentStream.flush();  
}  
protected void doClose() throws IOException {  
}  
protected void onWrite() throws IOException {  
}  
}  
}  

最新更新