【问题标题】:Closing connection - InputStream关闭连接 - InputStream
【发布时间】:2013-08-19 07:44:23
【问题描述】:

我需要在下载之前检查地址上的文件是否存在。它工作正常,直到它到达一些不存在的文件。 try-catch 块不能很好地解决它。当我打开连接(InputStream)时,它会尝试下载它,但失败并转到“catch”。但它不会关闭它的自我。下次我用相同的 IP 调用该方法时,它会崩溃并停止 - 同一 IP 上的连接太多(2)

总结:

直到它到达错误的地址,它工作正常

当它到达错误的地址时,它会去“catch”,但不会关闭它自己,它不能再连接了

public boolean exists(String URLName) throws IOException {
    boolean result = false;
    URL url = new URL(URLName);
    try {
        input = url.openStream();
        System.out.println("SUCCESS");
        result = true;
        input.close();
    } catch (Exception e) {
        input.close();
        System.out.println("FAIL");
    }
    return result;
}

我尝试了各种程序,但如果没有一些特殊的技巧,它将无法正常工作。请问,谁能帮我解决这个问题?

【问题讨论】:

  • 因为这是客户端代码,它不应该在一次连接失败后立即失败或阻塞。这是在 TIME_WAIT 阶段仍有许多失败连接的情况吗?

标签: java file url connection inputstream


【解决方案1】:

我会使用finally 块来关闭我的InputStream 并重构代码以改用URLConnection

例子:

public boolean exists(String URLName) throws IOException {
    boolean result = false;
    URLConnection connection = null;
    InputStream input = null;
    try {
    connection = new URL(URLName).openConnection();
        input = connection.getInputStream();
        System.out.println("SUCCESS");
        result = true;
    } catch (Exception e) {
        System.out.println("FAIL");
    } finally {
        if (input != null) {
            input.close();
        }
    }
    return result;
}

【讨论】:

  • 好一个..我想我会告诉而不是展示如何去做..
  • 当然,人们在提问时应该做的不仅仅是复制和粘贴......
  • 它不起作用...我那里的连接仍然太多...它不会下载下一个文件
【解决方案2】:

为什么不直接使用 finally 阻止并关闭其中的所有连接...??

【讨论】:

  • 我认为它也可以作为一种解决方案。不是吗?
  • 当我尝试关闭未打开的连接时,它会抛出 nullpointerex...
  • 确实如此,但答案应该更具描述性,并且需要强调您的工作。
【解决方案3】:

尝试使用新版本的apache HttpClient http://hc.apache.org/httpcomponents-client-ga/index.html,代码如下:

HttpClient httpClient = new HttpClient();
 GetMethod get = new GetMethod(url);
      try{
httpClient.executeMethod(get);


        return get.getResponseBodyAsString();


    } catch (HttpException clP_e) {

        throw new IOException(clP_e);

    } finally {

        get.releaseConnection();

    }

【讨论】:

猜你喜欢
  • 2019-07-27
  • 2016-04-05
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 2017-02-25
相关资源
最近更新 更多