I'm trying to add custom HTTP header to response in Apache CXF. I need to count MD5 from content and add it as a HTTP header. I tried to use ResponseHandler or Interceptor. My last try was
@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"));
}
}
but it does nothing.
Try to add Response Object
as your return value where you can set Headers..
Response.ok(/* some entity */).header("CustomHeader", "CustomValue").build();
You don't need to use interceptors
It sounds like you can accomplish this using the 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);
}
}
Don't forget to configure your interceptor in the cxf configuration file:
<jaxrs:server>
<jaxrs:outInterceptors>
<ref bean="md5OutInterceptor">
</jaxrs:outInterceptors>
</jaxrs:server>
<bean id="md5OutInterceptor" class="com.whatever.MD5OutInterceptor" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With