Swagger UI导致​​HTTP 406不能接受对生成除json之外的内容类型的操作的响应

时间:2015-06-18 22:06:18

标签: java rest jersey swagger swagger-ui

我在Jersey上发布了一个REST API,并在Swagger中进行了记录,我还有一个使用该API的Swagger UI安装。

我的几乎所有操作都生成application / json并按预期工作,除了一个GET操作产生:' text / plain; charset = utf-8'

当我尝试从Swagger UI调用服务时,服务器会记录javax.ws.rs.NotAcceptableException并返回406响应。如果我从REST客户端调用相同的服务,它将按预期工作。

display:none

如果我更改为@Produces(MediaType.APPLICATION_JSON +&#34 ;; charset = utf-8"),那么它可以正常工作,但我不想设置错误的内容类型。

问题似乎是Swagger UI错误地将Accept标头设置为application / json,这可以通过观察请求看到:

@GET
@Path("/text")
@Produces(MediaType.TEXT_PLAIN + ";charset=utf-8")
@ApiOperation(value= "Return text")
public Response getText(@QueryParam("user") String user) {
    return Response.ok(textService.getTextForUser(user)).build();
}

使用rest客户端时,Accept标头为:

GET /supertext/text?user=1
...
Accept: application/json

为什么Swagger UI没有正确设置Accept标头?

可以配置吗?

2 个答案:

答案 0 :(得分:2)

似乎swagger ui在发现@Produces注释包含单个值时将accept标头设置为application / json,否则它会在ui中呈现一个下拉列表,以便从可用的内容类型中进行选择。

在swagger-ui.js:

GET /supertext/text?user=1
...
Accept: */*

当下拉列表不存在时,该属性将变为未定义。

稍后在代码中,如果属性为null或未定义,则响应内容类型设置为application / json:

在swagger.js中:

opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();

所以我的解决方案是修改swagger-ui.js中的代码以确保设置了正确的内容类型,方法是浏览产生数组并选择第一个元素作为响应内容类型:

在swagger-ui.js中替换以下行:

if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") {
    if (this.opts.responseContentType) {
      responseContentType = this.opts.responseContentType;
    } else {
      responseContentType = "application/json";
    }
  }

使用:

opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();

答案 1 :(得分:0)

我也遇到了同样的问题,但是解决方案有所不同。

问题出在一个不相关的控制器中,该控制器的映射未正确定义。

在启动spring-boot应用程序时,我看到的日志如下:

([]) Mapping with class UnrelatedController

每当我加载swagger UI时,都会生成请求swagger的API,但是会显示对此API的响应,这与swagger的预期不符。

出现错误406

解决方案是更正UnrelatedController的映射,并且所有操作都像以前一样。感谢Git历史!