2010-07-02 125 views
9

我想在Apache CXF中將自定義HTTP頭添加到響應中。我需要從內容中計算MD5並將其添加爲HTTP標頭。我試圖使用ResponseHandler或攔截器。我最後的嘗試是如何將自定義HTTP標題添加到JAX-RS響應?

@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")); 

    } 

} 

但它什麼也沒做。

回答

11

嘗試添加Response Object爲您的返回值,你可以設置頁眉..

Response.ok(/* some entity */).header("CustomHeader", "CustomValue").build(); 

你並不需要使用攔截器

-1

檢查CustomOutInterceptor.java文件夾的src/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/ from 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。也試過這個,也無法讓它工作...

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" /> 
相關問題