首頁  >  文章  >  Java  >  api返回值的標準化的介紹(程式碼範例)

api返回值的標準化的介紹(程式碼範例)

不言
不言轉載
2019-03-08 16:26:253573瀏覽

這篇文章帶給大家的內容是關於api回傳值的標準化的介紹(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

api傳回值的標準化

例如

{"status":200,"message":"操作成功","data":"{\"id\":1,\"name\":\"张三\"}"}

封裝傳回物件

物件被封裝在base.util.ResponseUtils類型下,傳回值是標準的ResponseEntity對象,返回體
進行了二次封裝,主要有status,messsage和data組成,返回方法有ok和okMes​​sage,如果
真是返回訊息,不需要對象,可以選擇使用okMes​​sage,反之使用ok方法。

封裝的回傳物件:

  @Builder
  @Getter
  @NoArgsConstructor
  @AllArgsConstructor
  static class ResponseBody {

    private int status;
    private String message;
    private Object data;
  }

httpError和我們封裝的httpError

對http error來說有很多種,基本上可以設定為code在400到500之間的,像是客戶端參數問題就是400- bad request,而沒有認證就是401-Unauthorized,認證但沒有對應的權限就是403-Forbidden,請求的
資源沒有發現就是404-Not Found,請求方式錯誤(方法是post,你發起請求用了get)就是405- Method Not Allowed等。

  • 使用標準http回應狀態碼
  @GetMapping(GET_HTTP_ERROR)
  ResponseEntity getHttpError() throws IOException {
    return ResponseEntity.badRequest().build();
  }
  @Test
  public void getHttpError() throws Exception {
      mockMvc
          .perform(
              get(LindDemo.GET_HTTP_ERROR)
                  .accept(MediaType.APPLICATION_JSON_UTF8))
          .andExpect(status().is(400));
  
   }

回應的結果

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
  • 使用我們封裝的status狀態碼
#
  @GetMapping(GET_ERROR)
  ResponseEntity getError() throws IOException {
    return ResponseUtils.badRequest("传入的参数非法!");
  }
  
  @Test
    public void getError() throws Exception {
      mockMvc
          .perform(
              get(LindDemo.GET_ERROR)
                  .accept(MediaType.APPLICATION_JSON_UTF8))
          .andExpect(status().isOk());
  
    }

回應的結果

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"status":400,"message":"传入的参数非法!","data":{}}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

透過上面的回應結果可以看到,我們封裝的請求httpcode還是200,只不過把請求錯誤400狀態碼寫在了body
物件裡,目前這種方法用的比較多,像一些第三方介面用的都是這種方式,他們會規定對應的回應規範。

總結

事實上,兩個回應體都沒有問題,關鍵在於開發之間的規則要確定,不要在專案裡兩者兼用!

以上是api返回值的標準化的介紹(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除