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