在Android中处理RestClient调用的连接超时和读取超时

5

我有一个RestService接口,其中包含许多rest调用,我在整个应用程序中使用它。

我正在设置超时时间来处理连接读取超时

ClientHttpRequestFactory httpFactory = myRestService.getRestTemplate().getRequestFactory();
    if(httpFactory!=null)
    {
        if(httpFactory instanceof SimpleClientHttpRequestFactory)
        {
            ((SimpleClientHttpRequestFactory)httpFactory).setConnectTimeout(10*1000);
            ((SimpleClientHttpRequestFactory)httpFactory).setReadTimeout(30*1000);
        }
        else if(httpFactory instanceof HttpComponentsClientHttpRequestFactory)
        {
            ((HttpComponentsClientHttpRequestFactory)httpFactory).setConnectTimeout(10*1000);
            ((HttpComponentsClientHttpRequestFactory)httpFactory).setReadTimeout(30*1000);
        }
    }

但我遇到了处理超时情况的问题。 我考虑使用这种方法,但是当REST调用失败时,它没有进入此循环。

myRestService.getRestTemplate().setErrorHandler(new ResponseErrorHandler() 
    {
        @Override
        public boolean hasError(ClientHttpResponse paramClientHttpResponse) throws IOException 
        {
            Log.e(TAG, paramClientHttpResponse==null?"Null response" : ("Has Error : " + paramClientHttpResponse.getStatusText()+" , status code : "+paramClientHttpResponse.getStatusCode()));

            return false;
        }
        @Override
        public void handleError(ClientHttpResponse paramClientHttpResponse) throws IOException 
        {
            Log.e(TAG, paramClientHttpResponse==null?"Null response":("Handle Error : " + paramClientHttpResponse.getStatusText()+" , status code : "+paramClientHttpResponse.getStatusCode()));
        }
    });

有人能帮我解决这个问题吗?

1个回答

9

超时、网关错误、主机未找到及其他套接字异常无法通过ErrorHandlers进行覆盖。ErrorHandlers的目标是根据ResponseErrorHandler方法签名中所述,在现有的响应中查找错误。

所有套接字异常都会抛出RestClientException,必须在每个RestTemplate操作(例如try...catch块中的getForObject())中捕获。

try {
    repr = myRestService.getRestTemplate().getForObject(url, responseType, vars);
} catch (RestClientException e) {
    //Further exception processing, forming negative response should be here
}

请查看参考文档,了解相关的IT技术。

希望这能够对你有所帮助。


谢谢@alexei的回复和建议。我已经添加了那个标签。关于问题,我像你解释的那样处理REstClientException。我需要的是尝试在处理程序中获取异常并在那里处理它。在出现SocketTimeoutExceptions的情况下,我想在客户端中优雅地处理它,并显示一条消息或类似内容。我在这个答案中进行了评论:https://dev59.com/-Ggu5IYBdhLWcg3wJT5I#14320675。请看一下..! - Aswathy P Krishnan
1
我已经找到了这个问题的请求,但是没有得到适当的回应。http://forum.springsource.org/showthread.php?98449-Socket-read-timeout-exception-handling-with-http-gateway - alexei burmistrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接