java api返回值的标准化详解

时间:2022-09-22 20:40:15

api返回值的标准化

例如

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

封装返回对象

对象被封装在base.util.responseutils类型下,返回值是标准的responseentity对象,返回体进行了二次封装,主要有status,messsagedata组成,返回方法有ok和okmessage,如果真是返回消息,不需要对象,可以选择使用okmessage,反之使用ok方法。

封装的返回对象:

?
1
2
3
4
5
6
7
8
9
10
@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响应状态码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@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));
 
}

响应的结果

?
1
2
3
4
5
6
7
8
9
mockhttpservletresponse:
   status = 400
 error message = null
   headers = {}
  content type = null
    body =
 forwarded url = null
 redirected url = null
   cookies = []

使用我们封装的status状态码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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());
 
}

响应的结果

?
1
2
3
4
5
6
7
8
9
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
对象里,目前这种方法用的比较多,像一些第三方接口用的都是这种方式,他们会规定相应的响应规范。

总结

事实上,两种响应体都没有问题,关键在于开发之间的规则要确定,不要在项目里两者兼用!

以上所述是小编给大家介绍的java api返回值的标准化详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/lori/p/10494923.html