如果URL连接超过5秒,我想返回false - 如何使用Java?这是我用来检查URL是否有效的代码
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
答案 0 :(得分:186)
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;
}
答案 1 :(得分:104)
你可以像这样设置超时,
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);
答案 2 :(得分:1)
如果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;
};
}
答案 3 :(得分:-2)
我可以通过添加简单的线
来解决类似的问题HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
我的要求是知道响应代码,因为只是获取元信息就足够了,而不是获得完整的响应体。
默认请求方法是GET,并且需要花费大量时间才能返回,最后抛出了SocketTimeoutException。当我将请求方法设置为HEAD时,响应非常快。