3 回答
TA贡献2012条经验 获得超12个赞
HttpURLConnection有一个setConnectTimeout方法。
只需将超时设置为5000毫秒,然后捕获 java.net.SocketTimeoutException
您的代码应如下所示:
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
TA贡献1864条经验 获得超2个赞
如果HTTP连接没有超时,则可以在后台线程本身(AsyncTask,Service等)中实现超时检查器,以下类是Customize AsyncTask的示例,该示例在特定时间段后超时
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
一个样品
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
TA贡献1856条经验 获得超11个赞
我可以通过添加简单的行来获得针对此类类似问题的解决方案
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
我的要求是知道响应代码,为此,仅获取元信息就足够了,而不是获取完整的响应正文。
默认的请求方法是GET,要花很多时间才能返回,最后抛出了SocketTimeoutException。当我将Request Method设置为HEAD时,响应速度非常快。
添加回答
举报