HttpURLConnection超时设置

问题描述 投票:111回答:4

如果URL连接超过5秒,我想返回false - 使用Java可以实现这一点吗?这是我用来检查URL是否有效的代码

HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
java url timeout
4个回答
185
投票

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



104
投票

你可以像这样设置超时,

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

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

-2
投票

我可以通过添加一条简单的线来解决类似的问题

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

我的要求是知道响应代码,只是获取元信息就足够了,而不是获得完整的响应体。

默认的请求方法是GET,这需要花费大量的时间来返回,最后抛出了我的SocketTimeoutException。当我将请求方法设置为HEAD时,响应非常快。

© www.soinside.com 2019 - 2024. All rights reserved.