Java 如何获得响应体以改造异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23073439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:28:06  来源:igfitidea点击:

How to get response body to retrofit exception?

javaandroidrestretrofitokhttp

提问by Satya Swaroop Boddu

I am trying to connect to rest service via retrofit in android application. I am getting responses. But when there is some error response from the service, conversion exception occurs and now I want to do some actions based on the response body. But I am getting response body as NULL. But retrofit log has a error message. Why is this happening.

我正在尝试通过在 android 应用程序中进行改造来连接到休息服务。我正在收到回复。但是当服务有一些错误响应时,会发生转换异常,现在我想根据响应正文执行一些操作。但是我得到的响应体为 NULL。但是改造日志有一个错误信息。为什么会发生这种情况。

D/Reftofit log(24856): OkHttp-Received-Millis: 1397527055676
D/Reftofit log(24856): OkHttp-Response-Source: NETWORK 200
D/Reftofit log(24856): OkHttp-Sent-Millis: 1397527055492
D/Reftofit log(24856): Server: Apache/2.2.22 (Ubuntu)
D/Reftofit log(24856): X-Powered-By: PHP/5.3.10-1ubuntu3.10
D/Reftofit log(24856): {"result":"Invalid Token ID"}

Code:

代码:

public void failure(RetrofitError retrofitError) {
    String response = null;
    TokenError tokenError = (TokenError) retrofitError.getBodyAs(TokenError.class);
    response = tokenError.getErrorDetails();
    Log.e(TAG, response);
    if (response != null && response.contains("Invalid Token ID")) {
        GroupDataProvider.getInstance().onFailure();
    }

}

Here I am getting tokenErroras null. I don't know why? Do I need to set something with rest adapter so that the response will be passed to retrofit error object.

在这里,我越来越tokenErrornull. 我不知道为什么?我是否需要使用 rest 适配器设置一些东西,以便将响应传递给改造错误对象。

采纳答案by Cabezas

Try this code:

试试这个代码:

@Override
public void failure(RetrofitError error) {
    String json =  new String(((TypedByteArray)error.getResponse().getBody()).getBytes());
    Log.v("failure", json.toString());
}

with Retrofit 2.0

使用改造 2.0

@Override
public void onFailure(Call<Example> call, Throwable t) {
    String message = t.getMessage();
    Log.d("failure", message);
}

回答by Sergii Pechenizkyi

Your server should return 4xx HTTP error code to get this working.

您的服务器应返回 4xx HTTP 错误代码以使其正常工作。

When your server returns HTTP 200 this mean successful response and it will be processed with onSuccessbranch. Likely your object which you pass to Callback<Object>should be ready to handle both success and error result.

当您的服务器返回 HTTP 200 时,这意味着成功响应,它将被onSuccess分支处理。可能您传递给的对象Callback<Object>应该准备好处理成功和错误结果。

To make sure this is the case you can check if RetrofitErroris actually a JsonParseExceptionby adding next snippet:

为了确保是这种情况,您可以通过添加下一个片段来检查是否RetrofitError确实是 a JsonParseException

public void failure(RetrofitError error) {
    Log.v(TAG, error.getMessage());
};

回答by LOG_TAG

you need use getErrorStream() for this.

为此,您需要使用 getErrorStream()。

If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields().

如果 HTTP 响应表明发生了错误,getInputStream() 将抛出 IOException。使用 getErrorStream() 读取错误响应。可以使用 getHeaderFields() 以正常方式读取标头。

Ref: github issue

参考:github问题

回答by Victor Ponomarenko

if error in String format:

如果字符串格式错误:

public Sring getErrorBodyAsString(RetrofitError error) {    
      return (String) error.getBodyAs(String.class)
}

if you need custom object:

如果您需要自定义对象:

class ErrorResponse {
   @SerializedName("error")
   int errorCode;

   @SerializedName("msg")
   String msg;
}

public T getErrorBody(RetrofitError error, Class<T> clazz) {    
      return (T) error.getBodyAs(clazz);
}