Spring返回自定义header及Content-type

在使用Spring中, 如果直接对Resopnse中的content-type赋值,会被系统忽略, 如:

 @GetMapping("/e2")
 public String getE2( HttpServletResponse response) throws IOException {
   response.setHeader("content-type", "application/x-javascript; charset=gb2312");
   response.setHeader("selfHeader","selfHeaderValue");
   return "common body";
  }
    //返回值   

此时Response描述如下

Content-Length: 11
Content-Type: text/html;charset=UTF-8
Date: Fri, 10 Aug 2018 01:11:47 GMT
selfHeader: selfHeaderValue

如果业务需要设置自定义content-type可以使用如下两种方法

方法一 使用Response.getOutputStream

  @GetMapping("/e3")
  @IgnoreSecurity
  public void getE3(HttpServletResponse reponse) throws IOException {
      reponse.setHeader("content-type", "application/x-javascript; charset=gb2312");
      reponse.setHeader("selfHeader","selfHeaderValue");
      reponse.getOutputStream().print("this is body");
  }

返回结果如下;

Content-Length: 12
Content-Type: application/x-javascript;charset=gb2312
Date: Fri, 10 Aug 2018 01:29:46 GMT
selfHeader: selfHeaderValue

方法二,使用ResponseEntity

  @GetMapping("/e")
   public ResponseEntity<String> getE() {
       HttpHeaders headers = new HttpHeaders();
       headers.add("head1", "head1value");
       headers.add("Content-Type", "application/x-javascript; charset=gb2312");
       return ResponseEntity.status(200).headers(headers).body("this is body");
   }

返回结果如下;

Content-Length: 12
Content-Type: application/x-javascript;charset=gb2312
Date: Fri, 10 Aug 2018 01:31:52 GMT
head1: head1value
阅读更多

没有更多推荐了,返回首页