2014-09-22 118 views
1

尝试向我的宁静服务收到的每个请求添加标头。下面的入站http拦截器被调用,但不会添加标头。http请求拦截器 - 使用cxf的restful web服务

package com.client.interceptors; 

    import java.util.Collections; 
    import java.util.List; 
    import java.util.Map; 

    import org.apache.cxf.interceptor.Fault; 
    import org.apache.cxf.message.Message; 
    import org.apache.cxf.phase.AbstractPhaseInterceptor; 
    import org.apache.cxf.phase.Phase; 

    public class ClientInterceptor extends AbstractPhaseInterceptor<Message> { 
     public ClientInterceptor() { 
      super(Phase.PRE_INVOKE); // Put this interceptor in this phase 
      System.out.println("inside constructor"); 
     } 

     public void handleMessage(Message msg) throws Fault { 
      // process the message 

      System.out.println("inside interceptor"); 
      Map<String, List> headers = (Map<String, List>) msg 
      .get(Message.PROTOCOL_HEADERS); 

      headers.put("token", 
      Collections.singletonList("abcd1234xyz56sa")); 

      msg.put(Message.PROTOCOL_HEADERS, headers); 

     } 
    } 

这是如何实现的?

+0

但是你调用宁静的web服务? – Krishna 2014-09-22 05:15:48

+0

是的,这是一个简单的GET服务,我从浏览器调用 – skonka 2014-09-22 05:20:01

+0

如果你只是想从浏览器中醒来,那么你可以使用工具为同一个海报:) – Krishna 2014-09-22 05:21:59

回答

0

嗯雅我有一个相同的解决方案。看看这个。它可能会有帮助。

Client client = Client.create(); 
    WebResource webResource =client.resource("URL"); 

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); 
    queryParams.add("json", js); //set parametes for request 

    appKey = "Addkey " + appKey; // appKey is unique number 

    //Get response from RESTful Server get(ClientResponse.class); 
    ClientResponse response = null; 
    response = webResource.queryParams(queryParams) 
          .header("Content-Type", "application/json;charset=UTF-8") 
          .header("Authorization", appKey) 
          .get(ClientResponse.class); 

    String jsonStr = response.getEntity(String.class); 
+0

谢谢,但这又把它关系到客户端。我想要做的就是在服务端添加它。无论我的客户是什么,应该添加它,无论是来自java rest客户端还是来自浏览器的ajax调用。 – skonka 2014-09-22 06:18:31

+0

意味着你需要添加它从客户端我的意思是当你叫地址不是吗?在客户端添加 – Krishna 2014-09-22 06:26:26

+0

不应该成为问题。我希望能够在服务器端添加,而不考虑客户端/请求。为了给出背景,我基本上构建了一个模拟休息服务,寻找这些头,因此宁愿在服务端添加,而不是客户端。 – skonka 2014-09-22 06:46:08