首页 > 技术 > httpclient连接超时设置

httpclient连接超时设置

2012年1月27日 发表评论 阅读评论

/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);

第一行设置ConnectionPoolTimeout:这定义了从ConnectionManager管理的连接池中取出连接的超时时间,此处设置为1秒。
第二行设置ConnectionTimeout:这定义了通过网络与服务器建立连接的超时时间。Httpclient包中通过一个异步线程去创建与服务器的socket连接,这就是该socket连接的超时时间,此处设置为2秒。
第三行设置SocketTimeout:这定义了Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间,此处设置为4秒。
以上3种超时分别会抛出ConnectionPoolTimeoutException,ConnectionTimeoutException与SocketTimeoutException。

 

httpclient post方法封装

public static String post(String url, NameValuePair... params) {
try {
// 编码参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // 请求参数
for (NameValuePair p : params) {
formparams.add(p);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
CHARSET);
// 创建POST请求
HttpPost request = new HttpPost(url);
request.setEntity(entity);
// 发送请求
HttpClient client = getHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
}
HttpEntity resEntity =  response.getEntity();
return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (ClientProtocolException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (IOException e) {
throw new RuntimeException("连接失败", e);
}

}

分类: 技术 标签: ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.