java 带有响应参数的方法中的 IllegalStateException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36946178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:01:38  来源:igfitidea点击:

IllegalStateException within method with Response paramether

javajerseyjax-rsdropwizard

提问by VanDavv

I wrote a simple class to test response reading entity method (if it works as I expect). But it didn't worked well.

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

When I launch my class I get following error at response.readEntity():

当我启动我的课程时,我收到以下错误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)
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)

And here's the code I wrote

这是我写的代码

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));
    }

What am I doing wrong?

我究竟做错了什么?

回答by Paul Samsotha

There are two types of Responsees, inbound and outbound, though they still use the same interface. Outbound is when you are sending a response from the server

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

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

Inbound is when you are receiving the response on the client side.

入站是您在客户端收到响应的时间。

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

The readEntitymethod is disabled on the server side outbound response, because you don't need it. It is only used when you need to _de_serialize the response from the response stream. But there is none when it's outbound.

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

If you want the entity on the outbound response, just use Response#getEntity()

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