【问题标题】:IllegalStateException within method with Response paramether带有响应参数的方法中的 IllegalStateException
【发布时间】:2016-04-29 19:32:35
【问题描述】:

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

当我开始上课时,我在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));
    }

我做错了什么?

【问题讨论】:

    标签: java jersey jax-rs dropwizard


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

    • webTarged 应该是什么类型的对象?
    • WebTarget......
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 2018-10-16
      相关资源
      最近更新 更多