api返回值的標(biāo)準(zhǔn)化
例如
1
|
{ "status" : 200 , "message" : "操作成功" , "data" : "{\"id\":1,\"name\":\"張三\"}" } |
封裝返回對(duì)象
對(duì)象被封裝在base.util.responseutils類型下,返回值是標(biāo)準(zhǔn)的responseentity對(duì)象,返回體進(jìn)行了二次封裝,主要有status
,messsage
和data
組成,返回方法有ok和okmessage,如果真是返回消息,不需要對(duì)象,可以選擇使用okmessage
,反之使用ok
方法。
封裝的返回對(duì)象:
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
對(duì)于http error來(lái)說(shuō)有很多種,基本可以定為code在400到500之間的,像客戶端參數(shù)問(wèn)題就是400- bad request
,而沒(méi)有認(rèn)證就是401-unauthorized
,認(rèn)證但沒(méi)有對(duì)應(yīng)的權(quán)限就是403-forbidden
,請(qǐng)求的
資源沒(méi)有發(fā)現(xiàn)就是404-not found
,請(qǐng)求方式錯(cuò)誤(方法是post,你發(fā)起請(qǐng)求用了get)就是405- method not allowed
等。
使用標(biāo)準(zhǔn)http響應(yīng)狀態(tài)碼
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 )); } |
響應(yīng)的結(jié)果
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狀態(tài)碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@getmapping (get_error) responseentity<?> geterror() throws ioexception { return responseutils.badrequest( "傳入的參數(shù)非法!" ); } @test public void geterror() throws exception { mockmvc .perform( get(linddemo.get_error) .accept(mediatype.application_json_utf8)) .andexpect(status().isok()); } |
響應(yīng)的結(jié)果
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" : "傳入的參數(shù)非法!" , "data" :{}} forwarded url = null redirected url = null cookies = [] |
通過(guò)上面的響應(yīng)結(jié)果可以看到,我們封裝的請(qǐng)求httpcode還是200,只不過(guò)把請(qǐng)求錯(cuò)誤400狀態(tài)碼寫在了body
對(duì)象里,目前這種方法用的比較多,像一些第三方接口用的都是這種方式,他們會(huì)規(guī)定相應(yīng)的響應(yīng)規(guī)范。
總結(jié)
事實(shí)上,兩種響應(yīng)體都沒(méi)有問(wèn)題,關(guān)鍵在于開(kāi)發(fā)之間的規(guī)則要確定,不要在項(xiàng)目里兩者兼用!
以上所述是小編給大家介紹的java api返回值的標(biāo)準(zhǔn)化詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.cnblogs.com/lori/p/10494923.html