为什么程序需要检查 API header "Accept"

why does the program need to check API header "Accept"

我正在使用 swagger codegen 为我生成控制器。那里有一个 if 语句,但在我看来没有必要。谢谢。

        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json"))

Content-Type:它是一个header,它告诉在HTTP消息(包括请求和响应)中发送的数据的格式。

Accept:它是一个header,当浏览器(客户端)向网络服务器发出请求时,放在请求中。 这个 Accept header 只是意味着我(客户端)将只允许你这个数据类型作为响应。

如果服务器支持多种数据类型,服务器使用 accept header 像这样确定响应的数据类型,

@GetMapping("/someresources")
public ResponseEntity<String> getSomeresources(@RequestHeader("accept") String accept) {
        
        List<SomeResource> someresources = someService.someresources();
        
        //for react app
        if(accept.contains("application/json")) {
            SomeresourcesRepresentation representation = new SomeresourcesRepresentation(someresources);
            String serialziedRepresentaiton = jsonSerializer.serialize(representation);
            
            ResponseEntity<String> response = ResponseEntity
                    .status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(serialziedRepresentaiton);
            
            return response;
        } 

        //for web browser
        if(accept.contains("text/html")) {
            
            String html = "<!doctype html>"
                    + "<html>"
                    + "<head>"
                    + "<meta charset='UTF-8'>"
                    + "<title>summary</title>"
                    + "</head>"
                    + "<body>"
                    + "someresources size : "+someresources.size()
                    + "</body>"
                    + "</html>";
            
            ResponseEntity<String> response = ResponseEntity
                    .status(HttpStatus.OK)
                    .contentType(MediaType.TEXT_HTML)
                    .body(html);

            return response;
        }
        
        return ResponseEntity.notFound().build();
    }

你的 swagger 文档必须有类似于下面的 API 方法:

responses:
   "200":
     description: OK
     content:
       application/json:

据此,您的 API 的响应类型为 application/json:。但另外在未来,如果服务器决定产生一些其他类型的响应,如下所示:

 responses:
   "200":
     content:
       image/svg+xml:
         schema:
           type: string
       application/json:
         schema:
           $ref: "#/components/schemas/MyDto"

在这种情况下,决定响应接受参数的响应类型是必要的。所以在我看来,产生这种情况有两个原因:

  1. 客户端和服务器在返回内容方面有相同的合同。

  2. 如果明天添加新的内容类型,旧代码不会被破坏。