正常情況下镊辕,服務器返回200老厌,retrofit 可以正常解析到數(shù)據(jù)
但是有些服務器開發(fā)的二哥當業(yè)務出錯的時候省咨,http response code返回了非200逼肯,但是數(shù)據(jù)基本結(jié)構(gòu)沒有變化耸黑,只是少了data內(nèi)容,這會導致rx調(diào)用結(jié)果直接到了onError 里面了篮幢,這樣雖然能在onError里得到throwable對象中得到errorbody大刊,然后再轉(zhuǎn)換一次,但是不太優(yōu)雅洲拇,網(wǎng)上大不部分解決方案是這個奈揍,這里說一下我的思路,我覺得更簡單
比如正常情況下返回數(shù)據(jù)是這樣的,http response code 200,返回的數(shù)據(jù)如下
{
"code":0
"message":"success",
"data":{}
}
當出現(xiàn)錯誤時赋续,比如參數(shù)傳錯了,此時http response code 是其他的比如400
{
"code":2010
"message":"參數(shù)錯誤",
}
其實就是沒有data內(nèi)容另患,結(jié)構(gòu)不變纽乱,解決方法如下,
實現(xiàn)一個Interceptor子類(當然你要在okhttp初始化的時候昆箕,把這個Interceptor傳進去鸦列,而且我相信大多數(shù)項目中都至少會有一個Intercepter租冠,你要做的就是在你Intercepotr中加3行代碼),在intercept方法中拿到response對象(response = chain.proceed(request);就是這個玩意) 利用反射將response 的code 設(shè)置為200薯嗤,核心就三行代碼顽爹。
//處理非200的情況
Field codeFiled = response.getClass().getDeclaredField("code");
codeFiled.setAccessible(true);
codeFiled.set(response,200);
然后正常返回response。一切就OK了