Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java jdk URL应该如何关闭?_Java_Url_Connection - Fatal编程技术网

Java jdk URL应该如何关闭?

Java jdk URL应该如何关闭?,java,url,connection,Java,Url,Connection,我使用java.net.URL从internet获取html 我设置了keepAlive和maxConnections System.setProperty("http.keepAlive", "true"); System.setProperty("http.maxConnections","600"); 然后我开始从internet上获取html,并使用以下几个线程: protected static String content(URLConnection conn) throws IO

我使用
java.net.URL
从internet获取html 我设置了
keepAlive
maxConnections

System.setProperty("http.keepAlive", "true");
System.setProperty("http.maxConnections","600");
然后我开始从internet上获取html,并使用以下几个线程:

protected static String content(URLConnection conn) throws IOException {
    try (InputStream in = getInputStream(conn)) {
        //bla bla bla...
        // get bytes from in
        return new String(bytes, charset);
    }
}
但我发现当我运行这个程序一段时间(5-8小时)后,目标网站(用于测试)建立了760个连接


那么,我应该手动关闭URLConnection吗?老实说,您可以尝试使用Socket/ServerSocket而不是URLConnection-使用Sockets,您可以在选择时关闭套接字,这样您就可以更轻松地控制何时打开、关闭、读取和写入连接。查看API:


我从未见过使用API显式关闭连接的方法。但是,可以使用方法设置连接读取超时。这需要在建立连接之前进行设置。

谢谢,但这太复杂了,无法实现。。。。而您实际上并没有
close()
ing输入流?这将是第一件要做的事。你也应该限制对特定网站的并发请求;这是“Spidering 101”样式的基本操作,以限制负载。