有没有办法获取到泽西javax.ws.rs.Client的请求信息?

Is there a way to obtain the request information from javax.ws.rs.Client in Jersey?

我正在尝试为构建在 jersey 之上的项目制定日志记录标准,我想提供一种简单的方法来记录请求信息和响应,以防发生异常。下面的代码说明了我的想法:

    Client client = null;
    Response response = null;
    try {
        client = ClientBuilder.newClient();
        response = client.target("<URL>")
                .request(MediaType.APPLICATION_JSON)
                .post(entity);
    } catch( Exception ex) {
        //Send information for exception mapping to a JSON log
        throw new ServiceException( client,response );
    }

问题是如何在我的 ServiceException class 中获得以下内容:

    String url = client.getUri().toString(); //only one I could get using WebTarget
    MultivaluedMap<String, String> headers = client.getHeaders();
    String body = client.getEntity();
    MultivaluedMap<String, String> queryParams = client.getQueryParams();    
    String method = client.getMethod();

我尝试访问 WebTarget 但没有成功。

提前致谢!

泽西岛在客户端和服务器端都有 logging support。该文档显示了如何使用 Client 注册它。也可以用WebtTarget.

注册

如果您对结果不满意,并且想实现自己的,我将按照与 Jersey 相同的方式实现它:结合 WriterInterceptor 来记录请求实体流1 和一个 Client(Request|Response)Filter2 到获取请求和响应的其他部分(如 headers 和请求行)。

您可以查看 ClientLoggingFilter and the LoggingInterceptor 的源代码以获得一些实施思路。


1 - 它需要使用拦截器,而不是只对所有内容使用过滤器,因为过滤器只会给你 pre-seriazlied object,可以是任何东西,很难记录。使用输入流 .

进行通用日志记录更容易

2 - 请参阅 Filters and Interceptors