android http连接通常使用方式
URL url = new URL(path); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); } catch (IOException e) { Log.e(TAG, "openConnection() failed! url = " + url); e.printStackTrace(); return false; } try { conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { InputStream xmlStream = conn.getInputStream(); parserStates(xmlStream); } else { Log.e(TAG, "RequestMethod failed! code = " + conn.getResponseCode()); } } catch (ConnectTimeoutException e) { return false; } catch (IOException e) { e.printStackTrace(); return false; } if (conn != null) { conn.disconnect(); }
在设置超时时间的方法中,设置超时的时间3000,在阻塞的getResponseCode方法中时间不准。
这样采取org.apache.http.client.HttpClient方法
HttpParams httpParameters = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParameters, 500);HttpConnectionParams.setSoTimeout(httpParameters, 500);HttpGet httpget = new HttpGet(updateUrl.toURI());DefaultHttpClient httpClient = new DefaultHttpClient();httpClient.setParams(httpParameters);HttpResponse response = httpClient.execute(httpget);HttpEntity entity = response.getEntity();InputStream is = entity.getContent();//download file.....这种方法可以准备的计算阻塞时间