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/plain的MIME类型.
Accept: text/plain
下面的accept header会接受text/plain和text/html的MIME类型,这俩者直接并没有优先级.
Accept: text/plain, text/html
但是下面的客户端会会接受text/plain和text/html的MIME类型,但是text/html的优先级高于text/plain, 因为text/html有一个更高的q值. (默认情况下q=1)
Accept: text/plain; q=0.9, text/html
如果服务器能够同时提供text/plain和text/html, 那么在这个例子中,他就应该提供text/html.
通过使用produces方法设置了route产生的MIME类型, 例如下面的handler设置了一个MIME类型为application/json的响应
router.route().produces("application/json").handler(routingContext -> {HttpServerResponse response = routingContext.response();response.putHeader("content-type", "application/json");response.write(someJSON).end();});
在这个例子中,route会匹配到所有的accept header为application/json的请求.
下面是该accept headers的匹配值:
Accept: application/jsonAccept: application/*Accept: application/json, text/htmlAccept: application/json;q=0.7, text/html;q=0.8, text/plain
你还可以设置你的routeproduce多个MIME类型. 在这种情况中, 你可以使用getAcceptableContentType()方法找到实际接受到的MIME类型
router.route().produces("application/json").produces("text/html").handler(routingContext -> {HttpServerResponse response = routingContext.response();// Get the actual MIME type acceptableString acceptableContentType = routingContext.getAcceptableContentType();response.putHeader("content-type", acceptableContentType);response.write(whatever).end();});
在上面的例子中,如果你发送下面的accept header
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.
