如何在CXF拦截器中获取HTTP响应代码?

时间:2017-10-12 18:20:32

标签: java cxf interceptor

我有基于Apache CXF的Web服务。我编写了拦截器来记录一些包含http响应代码的特定内容。

public class MyOutInterceptor extends AbstractPhaseInterceptor<Message> {

    public MyOutInterceptor() {
        super(Phase.SEND);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);
        //...
    }
}

BUT !!! responseCodenull。即使我改变了拦截器阶段,它总是null 如何在CXF拦截器中获取http响应代码?

UPD 即可。应用程序Spring / CXF配置:https://gist.github.com/alexiuscrow/b5ceb2df7d652a77cd788454e0792211

UPD 即可。临时解决方案

@Override
public void handleMessage(Message message) throws Fault {
    Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);
    if (null == responseCode) {
        HttpServletResponseWrapper responseWrapper = 
           (HttpServletResponseWrapper) message.get(AbstractHTTPDestination.HTTP_RESPONSE);
        responseCode = responseWrapper.getStatus();
    }
    //...
}

1 个答案:

答案 0 :(得分:0)

确保您已为outinterceptor注册拦截器而不是outFaultInterceptor or FaultInterceptor等。以下是经过验证的示例。

import org.apache.cxf.annotations.Provider;
import org.apache.cxf.annotations.Provider.Type;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Provider(value=Type.OutInterceptor)
public class KpOutInterceptor2 extends AbstractPhaseInterceptor<Message> {

    private final static Logger LOG = LoggerFactory.getLogger(KpOutInterceptor2.class);

    public KpOutInterceptor2() {
        super(Phase.SEND);

    }   

    @Override
    public void handleMessage(Message message) throws Fault {
        LOG.info("JAXRS response status code is {}", message.get(Message.RESPONSE_CODE));
    }

}

或者更好的方法是使用JAXRS 2.0标准过滤器。

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Provider
public class KpOutInterceptor implements ContainerResponseFilter {

    private final static Logger LOG = LoggerFactory.getLogger(KpOutInterceptor.class);

    @Override
    public void filter(ContainerRequestContext reqCtx, ContainerResponseContext resCtx) throws IOException {

        LOG.info("JAXRS response status code is {}", resCtx.getStatus());

    }

}