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

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

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

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

@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();
}

如果我改为@Produces(MediaType.APPLICATION_JSON“; charset = utf-8”),那么它工作正常,但我不想设置错误的内容类型.

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

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

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

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

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

这可以配置吗?

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

在swagger-ui.js中:

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

如果下拉列表不存在,则属性将变为未定义.

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

在swagger.js中:

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

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

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

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

附:

if($("div select[name=responseContentType]", $(this.el)).val() === undefined) { 
    opts.responseContentType = opts.parent.model.produces[0];
}

else {
    opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();
}
点赞