设置DefaultHttpClient和HttpClient的超时时间的方法
转自:https://blog.csdn.net/sdujava2011/article/details/38921019
DefaultHttpClient超时设置:
1.其实是在HttpConnectionParams里设置的。我自己写了一个继承DefaultHttpClient的类,以后使用用这个就行了:
- /**
- * 封装超时的HTTPclient
- * @author wangfeng
- * @date date 2013-12-20 09:30:26
- */
- public class MyHttpClient extends DefaultHttpClient{
- /**
- * 获取 HttpClient,主要是封装了超时设置
- * @param rTimeOut 请求超时
- * @param sTimeOut 等待数据超时
- * @return
- */
- public DefaultHttpClient getHttpClient(int rTimeOut,int sTimeOut){
- BasicHttpParams httpParams = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParams, rTimeOut);
- HttpConnectionParams.setSoTimeout(httpParams, sTimeOut);
- DefaultHttpClient client = new DefaultHttpClient(httpParams);
- return client;
- }
- }
如何使用:
- HttpPost httpRequest =new HttpPost(validateUrl);
- //Post运作传送变数必须用NameValuePair[]阵列储存
- //传参数 服务端获取的方法为request.getParameter("name")
- List params=new ArrayList();
- params.add(new BasicNameValuePair("username",userName));
- params.add(new BasicNameValuePair("password",password));
- try{
- //发出HTTP request
- httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- //取得HTTP response
- HttpResponse httpResponse = null;
- try{
- httpResponse=new MyHttpClient().getHttpClient(7000,7000).execute(httpRequest);
- }catch(Exception e){
- isNetError = true;
- System.out.println("netError");
- }
2.
请求超时
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
DefaultHttpClient超时设置:
HttpClient httpClient=new HttpClient();
链接超时
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
读取超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000)
链接超时
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
读取超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000)