Java 改造连接失败返回 RetrofitError.response 为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24374482/
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-14 11:50:49  来源:igfitidea点击:

Retrofit connection failure returns RetrofitError.response as null

javaandroidretrofitokhttp

提问by Marc

Using Retrofit 1.6.0, OkHTTP 2.0.0, and OkHTTP-UrlConnection 2.0.0.

使用 Retrofit 1.6.0、OkHTTP 2.0.0 和 OkHTTP-UrlConnection 2.0.0。

I am doing a POST to a service using Retrofit to a URL that does not exist. The failure callback is called, as expected. However, the RetrofitError parameter does not have a response. I would really like to grab the HTTP status code that was returned by using

我正在使用 Retrofit 对不存在的 URL 执行 POST 服务。正如预期的那样,调用失败回调。但是,RetrofitError 参数没有响应。我真的很想获取使用返回的 HTTP 状态代码

error.getResponse().getStatus()

but since getResponse() returns null, I can't.

但由于 getResponse() 返回 null,我不能。

Why is getResponse() null and how can I get the status?

为什么 getResponse() 为 null 以及如何获取状态?

Thanks.

谢谢。

Also, the error I am receiving is UnknownHostException, as expected. Repeat: I am expecting this error. I want to know how to get the HTTP status code or why error.getResponse() returns null.

此外,正如预期的那样,我收到的错误是 UnknownHostException。重复:我期待这个错误。我想知道如何获取 HTTP 状态代码或为什么 error.getResponse() 返回 null。

Edit: Here's some code:

编辑:这是一些代码:

RestAdapterBuilderClass.java
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://badURL.DoesntMatter/");
            .setRequestInterceptor(sRequestInterceptor)
            .setLogLevel(RestAdapter.LogLevel.FULL)
             .build();
    sService = restAdapter.create(ServiceInterface.class);

ServiceInterface.java
    @POST("/Login")
    void login(@Body JsonObject body, Callback<String> callback);

CallbackClass.java
    @Override
    public void failure(RetrofitError error) {
        if (error.getResponse() == null) {

            // error.getResponse() is null when I need to get the status code
            // from it.

            return;
        }
    }

采纳答案by lyio

When you get an UnknownHostException it means, that you were not able to establish a connection to the server. You cannot, in fact, expect a HTTP status in that case.

当您收到 UnknownHostException 时,这意味着您无法与服务器建立连接。实际上,在这种情况下您不能期望 HTTP 状态。

Naturally you only get a Http response (and with that a status) when you can connect to a server.

当然,当您可以连接到服务器时,您只会收到 Http 响应(以及状态)。

Even when you get a 404 status code, you made a connection to the server. That is not the same as a UnknownHostException.

即使您收到 404 状态代码,您也已连接到服务器。这与 UnknownHostException 不同。

The getResponse() can return null if you didn't get a response.

如果您没有收到响应, getResponse() 可以返回 null。

回答by swanson

RetrofitErrorhas a method called isNetworkError()that you can use to detect a failed request due to network problems. I usually add a small helper method like this:

RetrofitError有一个方法isNetworkError()可以用来检测由于网络问题而失败的请求。我通常会添加一个像这样的小辅助方法:

public int getStatusCode(RetrofitError error) {
    if (error.isNetworkError()) {
        return 503; // Use another code if you'd prefer
    }

    return error.getResponse().getStatus();
}

and then use that result to handle any additional failure logic (logout on 401, display error message on 500, etc).

然后使用该结果来处理任何其他故障逻辑(在 401 上注销,在 500 上显示错误消息等)。

回答by mustaq

I am using Retrofit 2. When endpoint url end with "/" as in your case and again in your interface it starts with "/" [@POST("/Login")] causes this problem. Remove the "/" from .setEndpoint() method

我正在使用 Retrofit 2。当端点 url 以“/”结尾时,在你的情况下,再次在你的界面中,它以“/”开头 [@POST("/Login")] 会导致这个问题。从 .setEndpoint() 方法中删除“/”

回答by Peter File

Just to expand on @lyio's answer, I found from Fabric logging that getKind() sometimes returns UNEXPECTED and then if you parse the message you get timeouts and connection issues so I wrote the utility class below.

只是为了扩展@lyio 的答案,我从 Fabric 日志记录中发现 getKind() 有时会返回 UNEXPECTED,然后如果您解析消息,您会遇到超时和连接问题,因此我编写了下面的实用程序类。

public class NetworkUtils {
    // Compiled from Fabric events
    private static final List<String> networkErrorStrings = new ArrayList<>(Arrays.asList(
        "Unable to resolve host",
        "Connection closed by peer",
        "Failed to connect",
        "timeout",
        "Connection timed out"));

    public static boolean isNetworkError(@Nullable RetrofitError retrofitError) {
        if (retrofitError != null) {
            if (retrofitError.getKind() != RetrofitError.Kind.NETWORK) {
                for (String error : networkErrorStrings) {
                    if (retrofitError.getMessage().contains(error)) {
                        return true;
                    }
                }
            } else {
                return true;
            }
        }

        return false;
}

}

}