java create HTTP persistent connection

萝らか妹 提交于 2019-12-13 03:56:14

问题


I am trying to write a java program that will automatically download and name some of my favorite web comics. Since I will be requesting multiple objects from the same domain, I wanted to have a persistent http connection that I could keep open until all the comics have been downloaded. Below is my work-in-progress. How do I make another request from the same domain but different path without opening a new http connection?

import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL

public class ComicDownloader
{
    public static void main(String[] args)
    {
        URL url = null;
        HttpURLConnection httpc = null;
        BufferedReader input = null;

        try
        {
            url = new URL("http://www.cad-comic.com/cad/archive/2002");
            httpc = (HttpURLConnection) url.openConnection();
            input = new BufferedReader(new InputStreamReader(httpc.getInputStream()));
            String inputLine;

            while ((inputLine = input.readLine()) != null)
            {
                System.out.println(inputLine);
            }

            input.close();
            httpc.disconnect();
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }
    }
}

回答1:


As long as keep-alive is supported by the HTTP server, the implementation of HttpURLConnection will cache the underlying TCP connection and do that transparently for you.




回答2:


The support for HTTP keep-Alive is done transparently. However, it can be controlled by system properties http.keepAlive, and http.maxConnections, as well as by HTTP/1.1 specified request and response headers.

The system properties that control the behavior of Keep-Alive are:

http.keepAlive=(boolean) default: true

Indicates if keep alive (persistent) connections should be supported.

http.maxConnections=(int) default: 5

Indicates the maximum number of connections per destination to be kept alive at any given time

Taken from: Persistent Connections




回答3:


HTTP connections are stateless, so each new image you request will be a new URL and therefore a new connection.




回答4:


To utilize the java persistent Http connection, you should not close the HttpURLConnection (httpc in your case) and just close the Input stream as once you read all the data from the stream or close it. Java would clear the Socket connection and make it available for reuse.
As per jdk it uses the caching mechanism to reuse the same TCP connection. Calling disconnect() should not imply that this HttpURLConnection instance can be reused for other requests.



来源:https://stackoverflow.com/questions/10550364/java-create-http-persistent-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!