Java 如何处理 HTTP 超时?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18054631/
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
How to handle HTTP timeout?
提问by Louis Evans
In my application, I am downloading JSON data from a ReST web service. Most of the time, this works fine, however sometimes the connection will time out.
在我的应用程序中,我从 ReST Web 服务下载 JSON 数据。大多数情况下,这工作正常,但有时连接会超时。
This is the code I use to set the timeout...
这是我用来设置超时的代码...
HttpConnectionParams.setConnectionTimeout( httpParameters, 20000 );
HttpConnectionParams.setSoTimeout( httpParameters, 42000 );
If the connection times out, the application crashes and closes, how do I handle a time out?
如果连接超时,应用程序崩溃并关闭,我该如何处理超时?
回答by VM4
The HttpClient class throws a ConnectTimeoutException Exception, so you should listen for it:
HttpClient 类抛出 ConnectTimeoutException 异常,因此您应该监听它:
try {
HttpResponse response = client.execute(post);
// do something with response
} catch (ConnectTimeoutException e) {
Log.e(TAG, "Timeout", e);
} catch (SocketTimeoutException e) {
Log.e(TAG, " Socket timeout", e);
}
回答by Harish Godara
Increase your time of waiting for response like :
增加您等待响应的时间,例如:
HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 ); //1 minute
HttpConnectionParams.setSoTimeout( httpParameters, 90000 ); // 1.5 minute
回答by Louis Evans
I have tried to catch a variety of exception types, I have found that catching an IOException worked as I wanted!
我尝试捕获各种异常类型,我发现捕获 IOException 可以按我的意愿工作!