Java创建HTTP持久连接 [英] java create HTTP persistent connection

查看:162
本文介绍了Java创建HTTP持久连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Java程序,该程序将自动下载并命名一些我最喜欢的网络漫画.由于我要从同一个域请求多个对象,因此我希望有一个持久的http连接,在下载所有漫画之前,我可以一直保持打开状态.以下是我正在进行的工作.如何在不打开新的http连接的情况下,从相同域但路径不同发出另一个请求?

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

推荐答案

只要HTTP服务器支持keep-alive,HttpURLConnection的实现就会缓存基础的TCP连接,并为您透明地进行.

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.

这篇关于Java创建HTTP持久连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆