Resteasy客户端:如何设置上下文参数

时间:2018-03-24 16:30:26

标签: jax-rs resteasy

我使用Resteasy客户端为我的服务运行测试用例。在应用程序中我们在会话检查过滤器中设置了上下文Params(实现了ContainerRequestFilter)。我试图在Resteasy客户端中使用添加ClientRequestFilter实现,但在服务调用中无法识别该属性。

// Resteasy客户端调用逻辑

ResteasyClient resteasyClient = new ResteasyClientBuilder().build();
        resteasyClient.register(new MyClientRequestFilter());
resteasyClient.target("http://localhost:" + port + "/myPath").request()
.post(Entity.json(authorization_reqParams)).readEntity(String.class));

//过滤

 public class MyClientRequestFilter implements ClientRequestFilter
    {

        @Override
        public void filter(ClientRequestContext requestContext) throws IOException
        {
       requestContext.setProperty("CUSTOMER_ATTRIBUTE", "myCustomValue");

        }
    }

//休息服务方法

     @POST
        @Path("/myPath")
        @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        public Response subpartner(Authorization_ReqParams authorizationReqParams, @Context HttpHeaders headers,
                @Context HttpServletRequest request, @Context HttpServletResponse response)
        {
        String myAttribute= request.getAttribute("CUSTOMER_ATTRIBUTE"); 
//myAttribute is returned as null always

        //additional logic

        }

我能够使用相同的实现设置& get Header参数,但Request param始终读为null。 如何设置请求上下文参数?

1 个答案:

答案 0 :(得分:0)

MyClientRequestFilter中,您向请求对象添加了一个属性。你真正想要的是发送一个标题。

请改为尝试:

@Override
public void filter(ClientRequestContext requestContext) {
    MultivaluedMap<String, Object> headers = requestContext.getHeaders();
    headers.add("CUSTOMER_ATTRIBUTE", "myCustomValue");
}

并按照以下方式阅读:

    @POST
    @Path("/myPath")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response subpartner(Authorization_ReqParams authorizationReqParams, @Context HttpHeaders headers,
                @Context HttpServletRequest request, @Context HttpServletResponse response)
        {
            String myAttribute= headers.getRequestHeader("CUSTOMER_ATTRIBUTE"); 

        //additional logic

        }