Spring返回自定义header及Content-type

编程知识 更新时间:2023-04-05 06:42:06

在使用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

更多推荐

Spring返回自定义header及Content-type

本文发布于:2023-04-05 06:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/53b8bce32880a1ced25aae33af3a2a7d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   Spring   header   type   Content

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45338文章数
  • 14阅读数
  • 0评论数