【问题标题】:Try Internet Connectivity only for few Seconds仅在几秒钟内尝试 Internet 连接
【发布时间】:2012-09-10 08:07:33
【问题描述】:

我正在尝试连接到必须获取数据的互联网,如果连接时间超过 5 秒,我必须完成该过程并继续离线工作。
一切正常,有时在互联网不可用时大约需要 10 秒到return,现在我必须在时间超过时间限制时返回xml == null;,
我不想在异步任务中这样做

    public String getUrlData(String url) {
    String xml = null;

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    System.out.println("waiting");
    HttpResponse httpResponse;

    try {
        // start the timer here

        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

        // check if the timer has exceeded by "if else"
        // move to "return xml;" Manually when exceeds 5sec, but how?

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return xml;

}

this answer之后的编辑代码

public String getUrlData(String url) {
    String xml = null;

    final int TIMEOUT_MILLISEC = 5000; // 5 seconds

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);
    System.out.println("waiting");
    HttpResponse httpResponse;

    try {
        // start the timer here
        System.out.println("Started");
        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Ended");
    return xml;

}

LogCat 在这里 >> 20 Secs

【问题讨论】:

  • 你是在真机还是模拟器上试过这个?在尝试使用 DefaultHttpClient 时,我注意到设置超时在模拟器中无法正常工作。它基本上只是忽略任何超时设置(另见this post)
  • 但是,我的要求不是这样,我需要一些东西来跳过我在 5 秒后执行 HTTP 请求并将 xml 返回为空。如果 xml 在 5 秒前返回,那么什么都不会发生。
  • 如果您按照 Waqas 的建议设置超时,您的 http-request 将在超时间隔后自动停止并抛出错误。您所要做的就是捕获错误并返回 null。我的观点是,这只适用于真实设备,而不适用于模拟器。

标签: java android multithreading concurrency


【解决方案1】:

您需要做的就是为您的连接定义一个超时限制。例如:

final int TIMEOUT_MILLISEC = 5000;  // 5 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpClient httpClient = new DefaultHttpClient(httpParams);

然后,以与使用它相同的方式使用httpClient。


编辑

public String getUrlData(String url) {
String xml = null;

final int TIMEOUT_MILLISEC = 5000;  // 5 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;

try {
    // start the timer here

    httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    xml = EntityUtils.toString(httpEntity);

    // check if the timer has exceeded by "if else"
    // move to "return xml;" Manually when exceeds 5sec, but how?

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return xml;

}

【讨论】:

  • 谢谢老兄,但这似乎不起作用请检查LogCat Here。还要检查我目前正在使用的更新代码。
  • ahaan 著名的 java.net.UnknownHostException :) 只需关闭并再次运行您的模拟器(也可能是 eclipse)然后清理您的项目并再次构建
  • 我明白这一点,但我想绕过第 5 秒和retrun xml==null 结束时的异常。更详细的解释,认为你在等一个人5秒,如果他不来你必须绕过,不管是什么异常,不要接受任何异常。 5 秒后返回 xml。
  • 您现在正在做的事情几乎可以满足您的需求。但是,如果您愿意,只需添加一个 catch 块 (catch(Exception ex){ /* do nothing */ }),它什么也不做,只会默默地吃掉所有类型的异常并返回 null
  • 但是,我的要求不是这样,我需要一些东西来跳过我在 5 秒后执行 HTTP 请求并将 xml 返回为空。如果在 5 秒内获取 HTTP 值,则 xml 已经返回某个值,因此必须退出 5 秒计时器。如果您难以理解我的确切要求,请告诉我,我想您可以帮助我。
【解决方案2】:

这个怎么样:

Thread thread = new Thread() {
  @Override
  public void run() {
    // do the downloading thing..
  }
};
thread.start();
thread.join(5000);

【讨论】:

  • 问题是“不想在异步任务中执行此操作”。这就像 AsyncTask。 AsyncTask 是一个线程的包装器。
  • join() 使其同步
  • 这也受到您可能无法取消正在运行的代码这一事实的影响。理想情况下,如果连接返回并且线程仍然存在,您只需执行 thread.interrupt 即可。但是,thread.interrupt() 是一项协作工作,需要编写底层 Runnable 代码来处理它。像 Thread.sleep 这样的一些操作会为您执行此操作并引发 InterruptedException。像 java.io 流这样的其他流则没有,您必须明确地继续检查 Thread.currentThread().isInterrupted。按照其他人的建议设置套接字超时更安全。
【解决方案3】:

这只是一个想法,但您可以设置一个延迟运行并在 5 秒后检查文件是否有任何大小。

【讨论】:

    【解决方案4】:
     HttpParams params = new BasicHttpParams();
    
        // Turn off stale checking.  Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
    
        HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
        HttpConnectionParams.setSocketBufferSize(params, 8192);
    
        // Don't handle redirects -- return them to the caller.  Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, false);
    
        // Use a session cache for SSL sockets
        SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    
        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http",
                PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https",
                SSLCertificateSocketFactory.getHttpSocketFactory(
                SOCKET_OPERATION_TIMEOUT, sessionCache), 443));
    
        ClientConnectionManager manager =
                new ThreadSafeClientConnManager(params, schemeRegistry);
    
        // We use a factory method to modify superclass initialization
        // parameters without the funny call-a-static-method dance.
        return new AndroidHttpClient(manager, params);
    

    根据需要更改 SOCKET_OPERATION_TIMEOUT 值。

    【讨论】:

      【解决方案5】:

      这段代码可以帮助你

      上一个答案中的这段代码是好的

      final int TIMEOUT_MILLISEC = 5000;  // 5 seconds
      
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
      
      HttpClient httpClient = new DefaultHttpClient(httpParams);
      

      只有当您尝试执行您的请求时,您才需要关心另外 3 个例外 SocketTimeoutException、UnknownHostException、ConnectTimeoutException

      所以也要抓住这 3 个例外。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 2020-08-23
        相关资源
        最近更新 更多