Android http请求数据 设置超时

以前一直在写http请求,设置超时也没怎么认真测试过,今天项目不怎么忙,写了一个http请求测了一下发现以前设置的超时根本没起作用,原来是在发送请求之后设置的超时时间,说着比较迷糊,还是直接上代码。

http请求代码:

/**
	 * http Post请求的过程
	 * @param postParameters:请求服务端接口需要的数据
	 * @param url:请求接口的地址
	 * @return result
	 */
	private static String requestPost(List postParameters,String url) {
		String result = null;
		BufferedReader in = null;
		try {
			HttpClient client = new DefaultHttpClient();
			//Represents a collection of HTTP protocol and framework parameters
			HttpParams params = null;
			params = client.getParams();
			//set timeout
			HttpConnectionParams.setConnectionTimeout(params, 5000);
			HttpConnectionParams.setSoTimeout(params, 35000);
			// url为访问地址
			HttpPost request = new HttpPost(url);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParameters,"utf-8");
			request.setEntity(formEntity);
			// 通过execute()执行httppost调用
			HttpResponse response = client.execute(request);
			
			// 读取返回结果
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			// 换行操作
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
			Log.d("返回数据", result);
		} catch (Exception e) {
			result = "NetError";
			Log.i("Error", "Exception"+e.getMessage());
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

其实执行请求就是client.execute(request);将设置超时放在执行之前就OK了,可以控制超时随心所欲了,以前一直没注意这个问题,看了一下以前的代码,有好几处写在了execute()之后,所以感觉上是控制时间老不对,其实走的超时是默认的超时!不知道童鞋们有没有遇到同样的问题!

你可能感兴趣的:(Android)