1. 程式人生 > >httpclient如何實現在一個連線中傳送多次請求

httpclient如何實現在一個連線中傳送多次請求

public class Sample {

    private static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(
                final HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;

        }

    };

    public static String Get(CloseableHttpClient http, String url){
        HttpGet httpget = new HttpGet(url);


        System.out.println("Executing request " + httpget.getRequestLine());

        String html = "";

        try{
            html = http.execute(httpget, responseHandler);
        }finally{
            return html;
        }
    }

    public static void main(String[] args) throws Exception {
        CloseableHttpClient http = HttpClients.createDefault();
        try {
            Get(http, "http://www.qq.com/111.txt");
            Get(http, "http://www.qq.com/222.txt");
            Get(http, "http://www.qq.com/333.txt");
        } finally {
            http.close();
        }
    }
}

只有同一個網站,且支援 keepalive 的情況下,才可以用同一個連線.

使用的是 httpclient-4.5.1, 下載地址: http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.1-bin.tar.gz