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

Android. Retrofit 2 beta-4. Get error string body

我使用 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":"Validation error"}

我试过这种方法:

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 解决了它(根据 ):

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) {
        //
    }
}

试试这个

response.errorBody();

response.message();

也许你应该使用 response.errorBody() 而不是 response.raw().body()。 这是 Retrofit 2 错误处理的更详细解释 .