2015-03-31 91 views
2

我正在使用Robospice(1.4.14)的Retrofit(1.6.1)從某些服務獲取數據(響應應該使用JSON)。改裝:當請求失敗時獲取原始響應主體

在某些情況下,我可能會收到一個HTML錯誤頁面而不是JSON響應。服務器返回一個200狀態碼,我不能改變它。在這種情況下,RoboSpice將調用onRequestFailure(SpiceException)方法。

在那裏,我能夠得到原來的RetrofitError excpetion,但身體是null。這是我如何得到它:

if (spiceException.getCause() instanceof RetrofitError) { 
    RetrofitError error = (RetrofitError) spiceException.getCause(); 
    error.getBody(); // returns null 
} 

調查改造的源代碼後,我發現,如果轉換失敗(這是這裏的情況,作爲改造預計JSON和接收HTML身體被替換null )。

RestAdapter下面一行是我的問題的根源:

response = Utils.replaceResponseBody(response, null); 

有沒有一種方法對身體沒有設置爲null?在另外一個SO問題中,我發現如果服務器返回4xx,則保持正文,但我無法更改。

回答

1

您應該創建一個改進的方法,只需返回retrofit.client.Response並在響應主體處於必要格式時手動調用轉換。

您更新接口:

... 
@GET("/foo/bar") 
Response fooBarMethod(Object foo, Object bar); 
... 

您RoboSpice要求:

... 
@Override 
public final FooBar loadDataFromNetwork() throws Exception { 
    Response r = getService().fooBarMethod(foo, bar); 
    if (isBodyInHtmlFormat()) { 
     // cool stuff 
     throw new ResponseIsHtmlException(); 
    } else { 
     // it is wise to make sure that it is 
     // exactly the same converter you are passing to 
     // your RetrofitSpiceService 
     Converter converter = createGsonConverter(); 
     return (FooBar) converter.fromBody(response.getBody(), FooBar.class); 
    } 
} 
+0

必須做一些重構,包括這一點,但它工作得很好。謝謝! – 2015-04-01 13:25:09