Jersey Client with Client Filter

时间:2013-01-17 11:15:26

标签: java web-services rest jersey

我正在使用Jersey客户端。

Client client = Client.create();
client.addFilter(new Myfilter());
// do some other things

和Myfilter Class

public class Myfilter extends ClientFilter {

    public ClientResponse handle(ClientRequest cr) {
         System.out.println("called");
         ClientResponse resp = getNext().handle(cr);
         return resp;
    }
}

我无法调用Myfilter的句柄方法。有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

Article说明了如何为泽西客户端添加过滤器。

希望有所帮助

P.S:如果您忘记将其添加到您的web.xml

<init-param>
  <param-name>your.package.ClientFilter</param-name >
</init-param>

实施例

@Override
    public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
        request.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "application/json");
        return getNext().handle(request);
    }

答案 1 :(得分:2)

这是一个简单的例子(使用jersey-client版本1.x),导致打印“调用”到控制台:

import com.sun.jersey.api.client.*;
import com.sun.jersey.api.client.filter.ClientFilter;

public class JerseyClientFilterExample {
    public static void main(String[] args) {
        Client client = Client.create();
        client.addFilter(new MyClientFilter());
        client.resource("http://google.com").get(ClientResponse.class);
    }
}

class MyClientFilter extends ClientFilter {
    @Override
    public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
        System.out.println("called");
        return getNext().handle(cr);
    }
}