Android的DefaultHttpClient中,超时设置需要调用HttpConnectionParams.setConnectionTimeout方法,如(以下代码的31~35行代码):
ref: Timeout in DefaultHttpClient Class Android
/**发送post请求的方法
* @param params 请求参数的键-值对.
* @param url
* @param encoding
* @param setTimeout 标识是否设置连接超时.
* @param connectionTimeout 如果设置连接超时,连接超时时间.
* @return
* @throws MalformedURLException
* @throws IOException
* @throws JSONException
* @throws ParseException
*/
private boolean postSend(final Map<String, String> params,
final String url, final String encoding, boolean setTimeout, final int connectionTimeout)
throws MalformedURLException, IOException, JSONException,
ParseException {
// 封装请求参数的键值对.
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
for (Entry<String, String> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), param
.getValue()));
}
// 封装请求参数的实体.
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,
encoding);
// 使用post请求.
HttpPost post = new HttpPost(url);
post.setEntity(entity);
// 使用DefaultHttpClient指定请求,以获取响应信息.
DefaultHttpClient client = new DefaultHttpClient();
//设置连接超时.
if(setTimeout) {
final HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
}
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), encoding));
// 使用线程安全的StringBuffer.
StringBuffer buffer = new StringBuffer();
String ln = null;
while ((ln = reader.readLine()) != null)
buffer.append(ln).append(System.getProperty("line.separator")); //根据操作系统平台换行.
// 传递json到Service处理.
final String rawJsonStr = buffer.toString();
//test only:
// Log.i("sysout", rawJsonStr);
resultAQIDays = convertJsonToAQIDayList(rawJsonStr);
return response.getStatusLine().getStatusCode() == 200; // 等于200表示发送成功.
}