查看原文:http://www.ibloger.net/article/156.html
HttpClient 4.3。HttpClient这货和Lucene一样,每个版本的API都变化很大,这有点让人头疼。就好比创建一个HttpClient对象吧,每一个版本的都不一样,
3.X是这样的
HttpClient httpClient=new DefaultHttpClient()
4.3是这样的
CloseableHttpClient httpClient = HttpClients.createDefault();
我要讲的是超时设置,HttpClient有三种超时设置,最近比较忙,没时间具体归纳总结,以后再补上,我这里就讲一些最简单最易用的超时设置方法。
这是个3.X的超时设置方法
HttpClient client = new HttpClient();
client.setConnectionTimeout(30000);
client.setTimeout(30000);
HttpClient httpClient= new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
4.X版本的超时设置(4.3后已过时)
HttpClient httpClient=new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
4.3版本超时设置
CloseableHttpClient httpClient = HttpClients.createDefault();
tpGet httpGet=new HttpGet("http://www.baidu.com");//HTTP Get请求(POST雷同)
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
httpClient.execute(httpGet);//执行请求Http
BTW,4.3版本不设置超时的话,一旦服务器没有响应,等待时间N久(>24小时)。