【问题标题】:class to read http pages with reliable timout that return `java.io.InputStream`类以可靠的 timout 读取返回 `java.io.InputStream` 的 http 页面
【发布时间】:2012-02-05 22:09:20
【问题描述】:

是否有任何类用于读取返回 java.io.InputStream 并且其超时可靠的 http 页面?
我试过java.net.URLConnection,但它没有可靠的超时(设置为超时需要更多时间)?我的代码在这里:

        URLConnection con = url.openConnection();
        con.setConnectTimeout(2000);
        con.setReadTimeout(2000);
        InputStream in = con.getInputStream();

【问题讨论】:

    标签: java http inputstream urlconnection


    【解决方案1】:

    我认为超时对您不起作用的原因是您在建立连接后设置超时,或者您使用了错误的设置器。您也可能使用“非标准”版本的 URLConnection ...

    “此方法的一些非标准实现会忽略指定的超时时间。要查看读取超时设置,请致电getReadTimeout()。”(或getConnectTimeout()

    如果您发布了实际代码的相关部分,我们可以为您提供更好的答案...


    或者,使用 Apache HttpClient 库。

    【讨论】:

    • 嗨,我使用的是 Sun 的版本,并且在从 URL 对象的 openConnection() 方法创建 URLConnection 对象后,我正在使用 setConnectTimeoutsetReadTimeout 方法设置超时。
    【解决方案2】:

    您可以使用 Apache HttpClient 来读取 http 页面,它还有一个 http 解析器。请检查此以获取更多信息reference about httpclient。您可以像这样使用他们的 API 获取 InputStream 对象。

    HttpClient httpclient = new DefaultHttpClient();
    
     // Prepare a request object
     HttpGet httpget = new HttpGet("http://www.apache.org/");
    
     // Execute the request
     HttpResponse response = httpclient.execute(httpget);
    
     // Examine the response status
     System.out.println(response.getStatusLine());
    
     // Get hold of the response entity
     HttpEntity entity = response.getEntity();
    
     // If the response does not enclose an entity, there is no need
     // to worry about connection release
     if (entity != null) {
         InputStream instream = entity.getContent();
    

    进入超时部分,它完全取决于网络,你不能从你的 java 代码中做很多事情。

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2019-07-15
      相关资源
      最近更新 更多