Is there a way to intercept the Jersey Client API both before and after the request?

时间:2015-07-13 21:00:09

标签: java jersey-client

I need to time the Jersey Client (v1.17). I see that I can use a filter to get the request but not the end of the call (response).

Doable?

1 个答案:

答案 0 :(得分:2)

得到它并且很尴尬它是多么容易......

public class JerseyClientFilter extends ClientFilter {

    @Override
    public ClientResponse handle(ClientRequest request) {
        long startTime = System.currentTimeMillis();

        // execute call...
        ClientResponse response = getNext().handle(request);

        // build log...
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP:").append(response.getStatus());
        sb.append(" - Time:[").append(System.currentTimeMillis() - startTime).append("ms]");
        sb.append(" - User:").append(this.findLogon(request));
        sb.append(" - Path:").append(request.getURI());
        sb.append(" - Content-type:").append(request.getHeaders().get(HttpHeaders.CONTENT_TYPE));
        sb.append(" - Accept:").append(request.getHeaders().get(HttpHeaders.ACCEPT));
        sb.append(" - RequestBody:").append(request.getEntity() != null ? request.getEntity().toString() : "none");
        sb.append(" - ResponseBody:").append(this.logResponse(response));

        new TmaticwsInfoEvent(TmaticwsConstants.LOG_OUTBOUND_REST, this, request.getMethod(), sb.toString());
        return response;
    }

所以你基本上扩展ClientFilter并像这样注入:this.theClient.addFilter(new JerseyClientFilter); BAM!

如果您真的想了解这一点,请查看Jersey“LoggingFilter”。那里有很多好东西......