【Android】PA4D_CH6 使用Internat资源

  1. android中,基本使用网络资源方式如下(同步)
    try {
          URL url = new URL(myFeed);
    
          // Create a new HTTP URL connection
          URLConnection connection = url.openConnection();
          HttpURLConnection httpConnection = (HttpURLConnection)connection;
    
          int responseCode = httpConnection.getResponseCode();
          if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConnection.getInputStream();
            processStream(in);
          }
        }
        catch (MalformedURLException e) {
          Log.d(TAG, "Malformed URL Exception.", e);
        }
        catch (IOException e) {
          Log.d(TAG, "IO Exception.", e);
        }
    
  2. 于此同时,android中解析XML主要有3种,分别为DOM解析器、SAX解析器和PULL解析器。
    1. DOM解析器,DomBuilder,通过DocumentBuilderFactory获取。这两个类都是javax包中定义的,不同于j2SE的是,android中重写了后者,直接获取了apache harmony的实现,不幸的是,harmony的项目在2011年时候已经被apache放弃了。
    2. SAX解析器。SAX是一个解析速度快并且占用内存少的xml解析器,非常适合用于Android等移动设备。 SAX解析XML文件采用的是事件驱动,也就是说,它并不需要解析完整个文档,在按内容顺序解析文档的过程中,SAX会判断当前读到的字符是否合法XML语法中的某部分,如果符合就会触发事件。所谓事件,其实就是一些回调(callback)方法,这些方法(事件)定义在ContentHandler接口。
      SAXParserFactory factory=SAXParserFactory.newInstance();  
      SAXParser parser=factory.newSAXParser();  
      MyHandel handel=new MyHandel ();  //此处MyHandle继承自DefaultHandel
      parser.parse(inputStream, handel);
      
    3. PULL解析器。以下来自android training,google比较推荐使用这个解析器
      为什么要学习PULL解析器呢?因为PULL解析是在XML文档中寻找想要的标记,把需要的内容拉入内存,而不是把整个文档都拉入内存,这种方式比较适合手机等内存有限的小型的移动设备。

      We recommend XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface:

发表评论

邮箱地址不会被公开。 必填项已用*标注