溫馨提示×

java返回responseentity怎么設置長度

小億
131
2024-05-16 14:09:13
欄目: 編程語言

在Java中,可以通過設置Content-Length頭來指定返回的ResponseEntity的長度。以下是一個示例代碼:

@GetMapping("/example")
public ResponseEntity<String> getExample() {
    String response = "This is an example response";
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(response.getBytes().length);
    
    return ResponseEntity.ok()
            .headers(headers)
            .body(response);
}

在上面的代碼中,我們首先創(chuàng)建了一個HttpHeaders對象,并調(diào)用setContentLength方法來設置返回內(nèi)容的長度。然后我們將這個HttpHeaders對象傳遞給ResponseEntity.ok().headers(headers).body(response)方法,以指定返回的ResponseEntity的長度。

0