android如何从网络中获取数据
android 因为整合了apache,所有支持所有的http请求,但作为嵌入式的终端,不仅需要支持get/post这种请求,
还需要支持不同的APN(CMNET/CMWAP),总得来说只要能连上了一个APN,其他网络都是可以调通的,第一需要底层
设置相关的参数(host, username/passwd, ip)。第二如果需要代理的,如cmwap需要添加相应的proxy,如下所示:
if (Constant.IS_CMWAP_APN) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(Constant.proxyUrl, Constant.proxyPort), new UsernamePasswordCredentials("cmwap", "cmwap")); HttpHost proxy = new HttpHost(Constant.proxyUrl, Constant.proxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
不然出现网络信号有了,就是拿不到数据,log中报socket timeout.你也可以通过在console端ping,看是不是有回包。
2. 由于网络数据太长,不可能一次性拿完,所有涉及到切割保存的问题,如果数据是中文,必须按照byte的形式保存,如果按照
下面的形式进行保存会有二个问题
A:中文乱码,如果返回是xml,会导致解析xml文件出错,因为一个文中字符占2个字节,readline时刚好把中文切掉半个,所以在
文档就会显示乱码,如果刚好是"<",">"就会出现解析错误。
B:效率太差,没有使用Buffer
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK) { HttpEntity en=response.getEntity(); String line = null; StringBuffer sb = new StringBuffer(); BufferedReader reader =null; if(contentEncoding != null && contentEncoding.equals("gzip")) { GZIPInputStream gin = new GZIPInputStream (en.getContent()); reader=new BufferedReader(new InputStreamReader(gin)); } else { reader = new BufferedReader(new InputStreamReader(en.getContent())); } while((line=reader.readLine())!=null) { sb.append(line); } line = sb.toString(); setResponseBody(line); en.consumeContent(); /*rxguang,add for perfermence,2010/04/09*/ sb = null; line = null; reader = null; en = null; }
通过下如下方式解析response是比较好的选择:
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 1.check content encoding type Header encodeHead = response.getFirstHeader("Content-Encoding"); if (encodeHead != null) { contentEncoding = encodeHead.getValue().trim(); } // 2.get http response content ByteArrayBuffer byteBuffer = new ByteArrayBuffer(BYTELENGTH); BufferedInputStream bis = null; InputStream is = null; byte[] contentByte; int byteReturnSize = 0; try { BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); is = bufHttpEntity.getContent(); bufHttpEntity.consumeContent();// confirm could read the all content // 3.use corresponding encode type to parse the content if (contentEncoding != null && contentEncoding.equals("gzip")) { GZIPInputStream gin = new GZIPInputStream(is); bis = new BufferedInputStream(gin); } else { bis = new BufferedInputStream(is); } contentByte = new byte[BYTELENGTH]; while ((byteReturnSize = bis.read(contentByte, 0, contentByte.length)) >= 0) { byteBuffer.append(contentByte, 0, byteReturnSize); } xmlBody = new String(byteBuffer.toByteArray()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (is != null) is.close(); } catch (Exception e2) { e2.printStackTrace(); } } }