HttpURLConnection超时问题

我想要返回false如果URL需要超过5秒连接 – 这怎么可能使用Java? 这是我用来检查URL是否有效的代码

HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 

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; }
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; } 

你可以像这样设置超时时间,

 con.setConnectTimeout(connectTimeout); con.setReadTimeout(socketTimeout); 

如果HTTP连接没有超时,你可以在后台线程本身(AsyncTask,Service等)中实现超时检查器,下面的类是定制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; }; }