3 回答

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
HttpURLConnection有一個(gè)setConnectTimeout方法。
只需將超時(shí)設(shè)置為5000毫秒,然后捕獲 java.net.SocketTimeoutException
您的代碼應(yīng)如下所示:
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貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果HTTP連接沒有超時(shí),則可以在后臺(tái)線程本身(AsyncTask,Service等)中實(shí)現(xiàn)超時(shí)檢查器,以下類是Customize AsyncTask的示例,該示例在特定時(shí)間段后超時(shí)
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);
}
一個(gè)樣品
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貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
我可以通過添加簡(jiǎn)單的行來獲得針對(duì)此類類似問題的解決方案
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
我的要求是知道響應(yīng)代碼,為此,僅獲取元信息就足夠了,而不是獲取完整的響應(yīng)正文。
默認(rèn)的請(qǐng)求方法是GET,要花很多時(shí)間才能返回,最后拋出了SocketTimeoutException。當(dāng)我將Request Method設(shè)置為HEAD時(shí),響應(yīng)速度非???。
添加回答
舉報(bào)