android httpclient 设置超时

3.X是这样的

HttpClient httpClient=new DefaultHttpClient();
4.3是这样的
CloseableHttpClient httpClient = HttpClients.createDefault();
当然,上面这些变化只不过是一些小变化,大家看看API大家就都会了。
我要讲的是超时设置,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();
HttpGet 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);//执行请求
BTW,4.3版本不设置超时的话,一旦服务器没有响应,等待时间N久(>24小时)

你可能感兴趣的