Jersey客户端请求中的多个返回类型

net*_*ger 4 rest client web-services jersey

我通过以下方式使用Jersey Client API: -

User user = webRsrc.accept(MediaType.APPLICATION_XML).post(User.class, usr);
Run Code Online (Sandbox Code Playgroud)

所以我期待User类的对象中的响应是一个JAXB注释类.但是,有时我可能会得到一个错误xml,为此我创建了一个JAXB类ErrorResponse.

现在的问题是,如果我的请求返回ErrorResponse的对象而不是User,我该如何处理?

我试过这样的 -

ClientResponse response=null;
try {

        response = webRsrc.accept(MediaType.APPLICATION_XML).post(ClientResponse.class,usr);
        User usr = response.getEntity(User.class);    
    }catch(Exception exp)
    {
       ErrorResponse err = response.getEntity(ErrorResponse.class);    
    }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在catch块中使用getEntity()时,它会抛出异常

[org.xml.sax.SAXParseException: Premature end of file.]
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:107)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:532)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:491) .....
Run Code Online (Sandbox Code Playgroud)

似乎在调用getEntity()一次之后,输入流已经耗尽.

Bri*_*zel 10

我认为你错过了整个"REST思维方式"的一个观点.
简答:是的,你只能调用一次getEntity.您需要检查返回的HTTP状态以了解应该获取的实体.

在服务器端:

  1. 在设计REST API时,应始终使用有关HTTP RFC的适当状态代码.
  2. 就此而言,请考虑使用ExceptionMapper接口(这里是一个带有"NotFoundException"示例)

因此,现在您的服务器返回带有User对象的"HTTP status OK - 200"或带有错误对象的错误状态.

在客户端:

您需要检查返回状态并根据API规范调整您的行为.这是一个快速而又脏的代码示例:

ClientResponse response=null;

response = webRsrc.accept(MediaType.APPLICATION_XML).post(ClientResponse.class,usr);

int status = response.getStatus();

if (Response.Status.OK.getStatusCode() == status) {

  // normal case, you receive your User object
  User usr = response.getEntity(User.class);

} else {

  ErrorResponse err = response.getEntity(ErrorResponse.class);
}
Run Code Online (Sandbox Code Playgroud)

注意:根据返回的状态代码,此错误可能非常不同(因此需要非常不同的行为):

  • 客户端错误40X:您的客户端请求错误
  • 服务器错误500:服务器端发生意外错误