带有 Response 参数的方法中的 IllegalStateException

IllegalStateException within method with Response paramether

我写了一个简单的 class 来测试响应读取实体方法(如果它按我预期的那样工作)。但是效果并不好

当我启动 class 时,我在 response.readEntity() 处收到以下错误:

Exception in thread "main" java.lang.IllegalStateException: Method not supported on an outbound message.  
  at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:150)

这是我写的代码

public static void main(String[] args) {
        List<Entity> representations = new ArrayList<>();
        representations.add(new Entity("foo", "baz", false));
        representations.add(new Entity("foo1", "baz1", true));
        representations.add(new Entity("foo2", "baz2", false));
        Response build = Response.ok(representations).build();
        printEntitesFromResponse(build);
    }

public static void printEntitesFromResponse(Response response) {
        response
                .readEntity(new GenericType<List<Entity>>() {})
                .stream()
                .forEach(entity -> System.out.println(entity));
    }

我做错了什么?

Response有两种类型,入站和出站,尽管它们仍然使用相同的界面。出站是当您从服务器端发送响应时

Response response = Response.ok(entity).build();

入站是指您在客户端接收响应。

Response response = webTarget.request().get();

readEntity() 方法在服务器端出站响应中被禁用,因为您不需要它。它仅在您需要 de 序列化来自响应流的响应时使用。但是出站的时候有none

如果您想要出站响应中的实体,只需使用 Response#getEntity()

您可以直接使用 Mockito 模拟响应。像这样

private final Response response = Mockito.mock(Response.class);

然后您可以在调用 readEntity 方法时模拟所需的响应。

Mockito.when(response.readEntity(String.class)).thenReturn("result");