简体   繁体   中英

jdk URL should and how to close?

I use java.net.URL to fetch html from internet I set keepAlive and maxConnections

System.setProperty("http.keepAlive", "true");
System.setProperty("http.maxConnections","600");

And then I start fetch html from internet with several threads things like:

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);
    }
}

But I found when I run this procedure for a while (5-8 hours), target website (for test) is Established 760 connections?

So , should I and how can I close URLConnection manually ?

To be honest, you might try using a Socket/ServerSocket instead of URLConnection - with Sockets, you can close the socket when you so choose, and it gives you a more down-and-dirty control over when to open, close, read, and write to a connection. Check out the API:

http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html

I have never seen a way to close the connection explicitly using its API. However, you can set the connection read timeout using setReadTimeout method. This need to be set before the connection is made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM