1. 程式人生 > >Spring返回自定義header及Content-type

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