Spring MVC 使用Java在Response Entity(Sping Boot )中设置Content-Length头

w80xi6nr  于 2023-08-06  发布在  Spring
关注(0)|答案(1)|浏览(252)

我想根据需要将content-length响应头设置为我的一个控制器。在参考了这两个问题(FirstSecond)之后,我可以理解设置响应头是至关重要的。但我确实需要这个。我的代码片段如下,

@GetMapping(value = /employees, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, List<Object>>> getEmployeeDetails(@RequestParam(value = "organization_id", required = false) Integer orgId) {

      Map<String, List<Object>> responseMap = //some method returns the data
      ObjectMapper objMapper = new ObjectMapper();
      String responseString = objMapper.writeValueAsString(responseMap);
      HttpHeaders httpHeaders = new HttpHeaders();
      httpHeaders.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(responseString.length()));
      return ResponseEntity.ok().headers(httpHeaders).body(responseMap);
}

字符串
在上述情况下,Content-Length计算不正确,响应json收缩。(即,如果Map包含50个对象,则响应在两者之间的某个位置收缩)
请帮助实现预期的结果。先谢了。

8zzbczxx

8zzbczxx1#

我对上面链接的其中一个问题的答案做了一些修改。下面的代码给了我正确的content-length header值,我的响应json被完全服务。

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/rest")
public class EmployeeController {
    @GetMapping(value = /employees, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, List<Object>>> getEmployeeDetails(@RequestParam(value = "organization_id", required = false) Integer orgId) throws IOException {
        Map<String, List<Object>> responseMap = //some method returns the data
        ObjectMapper objMapper = new ObjectMapper();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //getFactory() and createJsonGenerator() methods are deprecated
        JsonGenerator jsonGenerator = objMapper.getFactory().createGenerator(byteArrayOutputStream);
        objMapper.writeValue(jsonGenerator, responseMap);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_LENGTH,String.valueOf(byteArrayOutputStream.size()));
        return ResponseEntity.ok().headers(httpHeaders).body(responseMap);
    }
}

字符串

相关问题