Jersey Client: Logging HTTP Redirects

微笑、不失礼 提交于 2021-02-08 08:51:14

问题


I'm using JAX-RS with Jersey. When sending a POST request to an API, I receive a 302 and Jersey follows automatically which results in a 403. In my logging, however, I can only see the failed responses:

INFO Rest-Request:  POST http://[Jenkins-IP]/job/RestTestingArea/job/testJob/doDelete
INFO Rest-Response: POST 403 http://[Jenkins-IP]/job/RestTestingArea/job/testJob/doDelete

I have determined that in between request and response there is a redirect because when I turn off redirects, the logging output changes like this:

INFO Rest-Request:  POST http://[Jenkins-IP]/job/RestTestingArea/job/testJob/doDelete
INFO Rest-Response: POST 302 http://[Jenkins-IP]/job/RestTestingArea/testJob/doDelete

Is there any way to actually log those redirects aside from turning of redirects altogether and doing the second all myself? Logging:

public class LoggingFeature implements ClientRequestFilter, ClientResponseFilter
{
  private final Logger logger;

  public LoggingFeature(Logger log)
  {
    this.logger = log;
  }

  @Override
  public void filter(ClientRequestContext requestContext) throws IOException
  {
    try
    {
      logger.info(String.format("Rest-Request:  %s %s", requestContext
          .getMethod(), requestContext.getUri()));
    }
    catch (Exception ex)
    {
      logger.warn("LoggingFeature: ", ex);
    }
  }

  @Override
  public void filter(ClientRequestContext requestContext,
      ClientResponseContext responseContext) throws IOException
  {
    try
    {
      logger.info(String.format("Rest-Response: %s %d %s", requestContext
          .getMethod(), responseContext.getStatus(), requestContext.getUri()));
    }
    catch (Exception ex)
    {
      logger.warn("LoggingFeature: ", ex);
    }
  }
}

The Request:

    HttpAuthenticationFeature auth = HttpAuthenticationFeature.basicBuilder()
        .credentials(username, token)
        .build();
    Client client = ClientBuilder.newBuilder()
        .register(auth)
        .register(new LoggingFeature(LOG))
        .build();
    WebTarget deleteTarget = client.target("http://[Jenkins-IP]/job/RestTestingArea/job/testJob/doDelete").    
    Response response = deleteTarget.request()
        .post(null);

来源:https://stackoverflow.com/questions/60505516/jersey-client-logging-http-redirects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!