昨天看了一篇HttpClient的设置超时时间,本来以为今天到公司就能把问题给解决了。结果发现DefaultHttpClient没有设置超时时间。然后继续寻找,终于发现了DefaultHttpClient怎么设置超时的了。
其实是在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");
}