【问题标题】:Httpurlconnection timeout not happeningHttpurl连接超时没有发生
【发布时间】:2013-02-06 05:21:24
【问题描述】:

我有一个 java servlet 向其他服务器请求一些请求,而其他服务器有一个 apache 服务器,默认超时为 2 分钟。

我有两个要调用的 url,以防第一个 url 失败,然后我需要调用第二个 url,但是第一个 url 需要 2 分钟的默认时间超时。但是我不要求它像这样超时,比如10秒后如果没有得到结果,那么我需要调用第二个url

URL urlConnect = new URL(url.toString());
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
urlc.setConnectTimeout(1000*20);
urlc.connect();

【问题讨论】:

  • 我也尝试过 setreadtimeout,无论哪种情况都无法正常工作
  • 是的,NSURLConnection的setTimeout是不准确的,我们总是加个定时器来控制。

标签: java timeout httpurlconnection connection-timeout


【解决方案1】:

只捕获一个 SocketTimeoutException:

try{ 
         boolean timeout = false;
         URL urlConnect = new URL(url.toString());
         HttpURLConnection.setFollowRedirects(false);
         HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
         urlc.setConnectTimeout(10000); // 10 sec
         urlc.setReadTimeout(10000); // 10 sec
         urlc.connect();
       }catch(SocketTimeoutException e){
           timeout = true;
       }finally{
          if(timeout){
             handleSecoundRequestFunction(); //the same principle as by first connection
          }
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多