Android系统。改造2 beta-4。获取错误字符串正文

时间:2016-02-19 08:16:33

标签: android retrofit2

我使用Retrofit 2:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'

我添加了 okhttp3.logging.HttpLoggingInterceptor 来记录响应。我看到了我的日志:

D/OkHttp: <-- 400 Bad Request http://myurl.com/api/ (616ms)
D/OkHttp: Date: Fri, 19 Feb 2016 07:59:50 GMT
D/OkHttp: Server: Apache/2.4.12
D/OkHttp: X-Powered-By: PHP/5.4.45
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Connection: close
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: OkHttp-Sent-Millis: 1455868788858
D/OkHttp: OkHttp-Received-Millis: 1455868789211
D/OkHttp: {"error_message":"Validation error"}
D/OkHttp: <-- END HTTP (87-byte body)

如何从响应中获取错误正文字符串?在我的例子中,它是json字符串 - {“error_message”:“验证错误”}

我试过这种方式:

import retrofit2.Response;

Reader charStream = response.raw().body().charStream();
BufferedReader in = new BufferedReader(charStream);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
    sb.append(line);
}

但是我在这一行得到了IllegalStateException:

Reader charStream = response.raw().body().charStream();

FATAL EXCEPTION: main
java.lang.IllegalStateException: Cannot read raw response body of a converted body.
retrofit2.OkHttpCall$NoContentResponseBody.source(OkHttpCall.java:257)
at okhttp3.ResponseBody.byteStream(ResponseBody.java:69)
at okhttp3.ResponseBody.charStream(ResponseBody.java:100)
at com.myapp.delegate.retrofit.ApiDelegateRetrofit.parseError(ApiDelegateRetrofit.java:146)

修改

我已经为beta-4(根据https://stackoverflow.com/a/32896077/1225669)解决了这个问题:

if (response != null && response.errorBody() != null) {
    Converter<ResponseBody, ErrorData> errorConverter = retrofit.responseBodyConverter(ErrorData.class, new Annotation[0]);
    try {
        ErrorData error = errorConverter.convert(response.errorBody());
        return error;
    } catch (IOException e) {
        //
    }
}

2 个答案:

答案 0 :(得分:2)

可能你应该使用response.errorBody()而不是response.raw()。body()。 以下是Retrofit 2 erro handling Retrofit 2.0 how to get deserialised error response.body的更详细说明。

答案 1 :(得分:1)

试试这个

response.errorBody();

response.message();