Routing based on MIME types acceptable by the client

HTTP accept header常常用于表示客户端接收到的服务器响应的MIME类型.

accept header可以带有多个MIME类型,他们之间通过','分割.

MIME类型还可以有一个q值, MIME types can also have a q value appended to them* which signifies a weighting to apply if more than one response MIME type is available matching the accept header. The q value is a number between 0 and 1.0. If omitted it defaults to 1.0.

例如,下面的accept header表示只会接受text/plainMIME类型.

  1. Accept: text/plain

下面的accept header会接受text/plaintext/htmlMIME类型,这俩者直接并没有优先级.

  1. Accept: text/plain, text/html

但是下面的客户端会会接受text/plaintext/htmlMIME类型,但是text/html的优先级高于text/plain, 因为text/html有一个更高的q值. (默认情况下q=1)

  1. Accept: text/plain; q=0.9, text/html

如果服务器能够同时提供text/plaintext/html, 那么在这个例子中,他就应该提供text/html.

通过使用produces方法设置了route产生的MIME类型, 例如下面的handler设置了一个MIME类型为application/json的响应

  1. router.route().produces("application/json").handler(routingContext -> {
  2. HttpServerResponse response = routingContext.response();
  3. response.putHeader("content-type", "application/json");
  4. response.write(someJSON).end();
  5. });

在这个例子中,route会匹配到所有的accept headerapplication/json的请求.

下面是该accept headers的匹配值:

  1. Accept: application/json
  2. Accept: application/*
  3. Accept: application/json, text/html
  4. Accept: application/json;q=0.7, text/html;q=0.8, text/plain

你还可以设置你的routeproduce多个MIME类型. 在这种情况中, 你可以使用getAcceptableContentType()方法找到实际接受到的MIME类型

  1. router.route().produces("application/json").produces("text/html").handler(routingContext -> {
  2. HttpServerResponse response = routingContext.response();
  3. // Get the actual MIME type acceptable
  4. String acceptableContentType = routingContext.getAcceptableContentType();
  5. response.putHeader("content-type", acceptableContentType);
  6. response.write(whatever).end();
  7. });

在上面的例子中,如果你发送下面的accept header

  1. Accept: application/json; q=0.7, text/html

Then the route would match and acceptableContentType would contain text/html as both are acceptable but that has a higher q value.