java - 如果缺少@Produces 注释, Jersey 服务会返回什么?

标签 java rest jersey jax-rs restful-architecture

我开始学习 jersey for development restful web services。

正如我在大多数示例中注意到的那样使用了以下注释:

@Consumes

定义输入参数的格式

@Produces

定义输出参数的格式

但在实际代码中,我看到了如下所示的方法:

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/login")
public Response login(@FormParam("login") final String username, @FormParam("password") final String password){...}

我看到这个方法使用了 POST HTTP 方法。参数 userNamepassword 将具有根据 @Consumes(MediaType.APPLICATION_FORM_URLENCODED) 的形式。我看到了执行此方法的 URL。

但是我不明白这个方法返回的是什么。哪种格式?

最佳答案

我只是想澄清一下,“如果未指定,Jersey 默认会生成“application/octet-stream”” 并不完全正确。实际上在幕后发生了很多复杂的事情,这决定了最终的 Content-Type。 .正如规范中所述:

Note that the above (actually below :-) renders a response with a default media type of application/octetstream when a concrete type cannot be determined.

但是,正如我所说,有一种复杂的算法可以确定这种“具体类型”。我测试过的案例很少会返回 application/octet-stream .它如下(这直接来自规范。您可以尝试制作它的正面或反面,但它不适合外行):

3.8 Determining the MediaType of Responses

In many cases it is not possible to statically determine the media type of a response. The following algorithm is used to determine the response media type, Mselected, at run time:

  1. If the method returns an instance of Response whose metadata includes the response media type (Mspecified) then set Mselected = Mspecified, finish.

  2. Gather the set of producible media types P:

    • If the method is annotated with @Produces, set P = {V(method)} where V (t) represents the values of @Produces on the specified target t.
    • Else if the class is annotated with @Produces, set P = {V (class)}.
    • Else set P = {V (writers)} where 'writers' is the set of MessageBodyWriter that support the class of the returned entity object.
  3. If P = {}, set P = {'*/*'}

  4. Obtain the acceptable media types A. If A = {}, set A = {'*/*'}

  5. Set M = {}. For each member of A; a:

    • For each member of P; p:
      1. If a is compatible with p, add S(a; p) to M, where the function S returns the most specific media type of the pair with the q-value of a and server-side qs-value of p.
  6. If M = {} then generate a NotAcceptableException (406 status) and no entity. The exception MUST be processed as described in Section 3.3.4. Finish.

  7. Sort M in descending order, with a primary key of specificity (n/m > n/* > */*), a secondary key of q-value and a tertiary key of qs-value.

  8. For each member of M; m:

    • If m is a concrete type, set Mselected = m, finish.
  9. If M contains '*/*' or 'application/*', set Mselected = 'application/octet-stream', finish.

  10. Generate a NotAcceptableException (406 status) and no entity. The exception MUST be processed as described in Section 3.3.4. Finish.

你可以看到它并不像说它总是默认为 application/octet-stream 那样简单.简单的例子

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createCustomer(@FormParam("id") int id, 
                               @FormParam("name") String name) {
    return Response.ok("OK I GOT IT").build();
}

以上将返回 Content-Type: text/plain

假设您创建了一个 Customer对象并返回它

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createCustomer(@FormParam("id") int id, 
                               @FormParam("name") String name) {
    Customer customer = new Customer(id, name);
    return Response.ok(customer).build();
}

根据我的测试,它将返回 Content-Type: application/xml是的,正文内容 是 xml。

现在如果我们发送带有 Accept 的请求application/json 的标题,我们将得到 Content-Type: application/json 的响应头,因为是的,正文内容将是 json。这就是内容协商发挥作用的地方

如果我们只是用 201 Created 回应,这在 POST 中很常见/创建请求

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createCustomer(@FormParam("id") int id, 
                               @FormParam("name") String name) {
    return Response.created(someNewUri).build();
}

会有没有 Content-Type响应 header ,因为没有内容。

现在上面的一些例子不是很好的 REST 主要例子,但它表明,如果我们没有用 @Produces 显式地设置它,那么很多东西都会用于确定媒体类型。 .你必须考虑,响应的主体,可用 MessageBodyWriters , 你有 Content Negotiation考虑因素,以及规范中那个庞然大物中的任何其他内容。 (注意:我将“内容协商”链接加粗了,因为这是一个您在使用 REST 时应该真正熟悉的概念。它实际上在 JAX-RS/Jersey 中发挥了重要作用。

因此,您问题的真正答案是视情况而定。但希望您从这篇文章中获得了一些额外的知识:-)

关于java - 如果缺少@Produces 注释, Jersey 服务会返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27544242/

相关文章:

java - 为什么我不能有一个两层深度的内部类,其名称与其包含类相同?

java - 当 statusCode 断言失败并重新保证时打印响应正文

javascript - REST API 的 Web UI

java - 使用 Java 的 Web 服务计算器示例

java - 我应该在哪里关闭我的 activemq 连接(java,jersey)

java - 如何解决 "Can not find symbol"错误?

java - INSERT OR IGNORE 插入重复语句

java - Universal-Image-Loader 不保留显示的图像

java - 将curl http请求转换为Java的错误请求

java - Jersey 不应使用任何表单参数。异常(exception)