Persistent HttpURLConnection in Java

Viewed 30040

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

Even though HttpURLConnection enable keep-alive by default, it is not guaranteed that HttpURLConnection uses same TCP connection for multiple HTTP requests. I faced same kind of issue when writing HTTPS client application. Solved this issue by using single instance of SSLContext, SSLSocketFactory and HttpsURLConnection.

public class MyHTTPClient {
    private SSLContext mSSLContext = null;
    private SSLSocketFactory mSSLSocketFactory = null;
    private HttpsURLConnection mConnection = null;

    public void init() {
        //Setup SSL context and Socket factory here
    }

    pubblic void sendRequest() {
        URL url = new URL("https://example.com/request_receiver");
        mConnection = (HttpsURLConnection) url.openConnection();
        mConnection.setSSLSocketFactory(mSSLSocketFactory);

        // Setup request property and send request
        // Open input stream to read response
        // Close output, input streams
        
        mConnection.disconnect();
    }
}
Related