我正在尝试在Apache CXF中为响应添加自定义HTTP标头。我需要从内容中计算MD5并将其添加为HTTP标头。我尝试使用ResponseHandler或Interceptor。我的最后一次尝试是
@Component
public class ResponseBPAuthFilter extends AbstractOutDatabindingInterceptor {
public ResponseBPAuthFilter() {
super(Phase.MARSHAL_ENDING);
}
@Override
public void handleMessage(Message t) throws Fault {
Map headers = CastUtils.cast((Map)t.get(Message.PROTOCOL_HEADERS));
headers.put("Some-Header", Arrays.asList("test"));
}
}
但它什么也没做。
答案 0 :(得分:11)
尝试添加Response Object
作为返回值,您可以在其中设置标题..
Response.ok(/* some entity */).header("CustomHeader", "CustomValue").build();
您不需要使用拦截器
答案 1 :(得分:6)
听起来你可以使用CXF CachedOutputStream完成此任务。
public class MD5OutInterceptor extends AbstractPhaseInterceptor<Message> {
public MD5OutInterceptor () {
super(Phase.MARSHAL);
}
public final void handleMessage(Message message) {
OutputStream os = message.getContent(OutputStream.class);
if (os == null) {
return;
}
final CachedOutputStream cos = new CachedOutputStream(os);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cos.writeCacheTo(baos);
// calculate MD5
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] mdBytes = md.digest(baos);
MultivaluedMap<String, Object> headers = (MetadataMap<String, Object>) message.get(Message.PROTOCOL_HEADERS);
if (headers == null) {
headers = new MetadataMap<String, Object>();
}
headers.add("MD5-Header", new String(mdBytes));
message.put(Message.PROTOCOL_HEADERS, headers);
}
}
不要忘记在cxf配置文件中配置拦截器:
<jaxrs:server>
<jaxrs:outInterceptors>
<ref bean="md5OutInterceptor">
</jaxrs:outInterceptors>
</jaxrs:server>
<bean id="md5OutInterceptor" class="com.whatever.MD5OutInterceptor" />
答案 2 :(得分:-1)
检查文件夹 src / systests / jaxrs / src / test / java / org / apache / cxf / systest / jaxrs / 中的 CustomOutInterceptor.java 来自 cxf-2.3.3源代码分发的工作演示:
import javax.ws.rs.core.MultivaluedMap;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.impl.MetadataMap;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
public class MyOutInterceptor extends AbstractPhaseInterceptor<Message> {
public MyOutInterceptor() {
super(Phase.MARSHAL);
}
public void handleMessage(Message message) throws Fault {
MultivaluedMap<String, Object> headers = new MetadataMap<String, Object>();
headers.putSingle("BookId", "123");
message.put(Message.PROTOCOL_HEADERS, headers);
}
}
我猜您上次尝试时发布的代码来自1。一直在尝试这个,也无法让它工作......