簡體   English   中英

為什么程序需要檢查API頭“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 :它是一個標頭,它告訴 HTTP 消息(請求和響應)中發送的數據格式。

Accept :它是當從瀏覽器(客戶端)向 Web 服務器請求時放置在請求中的標頭。 這個 Accept 標頭僅僅意味着 I(client) 將只允許您將此數據類型作為響應。

如果服務器支持多種數據類型,服務器使用這樣的accept標頭確定響應的數據類型,

@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"

在這種情況下,需要在響應 Accept 參數中確定響應類型。 所以在我看來,產生這種情況有兩個原因:

  1. 該客戶端和服務器在返回內容方面具有相同的合同。

  2. 如果明天添加新內容類型,舊代碼不會中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM