【Android】PA4D_CH6 使用Internat資源

來源:互聯網
上載者:User

標籤:android   style   blog   class   code   java   

  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放棄了。
      HttpURLConnection httpConnection = (HttpURLConnection) connection;int responseCode = httpConnection.getResponseCode();if (responseCode == httpConnection.HTTP_OK) {    InputStream in = httpConnection.getInputStream();    DocumentBuilderFactory dbf = DocumentBuilderFactory                        .newInstance();    DocumentBuilder db = dbf.newDocumentBuilder();    // 分析input    Document dom = db.parse(in);    Element docEle = dom.getDocumentElement();}
    2. SAX解析器。SAX是一個解析速度快並且佔用記憶體少的xml解析器,非常適合用於Android等行動裝置。 SAX解析XML檔案採用的是事件驅動,也就是說,它並不需要解析完整個文檔,在按內容順序解析文檔的過程中,SAX會判斷當前讀到的字元是否合法XML文法中的某部分,如果符合就會觸發事件。所謂事件,其實就是一些回調(callback)方法,這些方法(事件)定義在ContentHandler介面。
      SAXParserFactory factory=SAXParserFactory.newInstance();  SAXParser parser=factory.newSAXParser();  MyHandel handel=new MyHandel ();  //此處MyHandle繼承自DefaultHandelparser.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:

      • KXmlParser via XmlPullParserFactory.newPullParser().
      • ExpatPullParser, via Xml.newPullParser().
            factory = XmlPullParserFactory.newInstance();      factory.setNamespaceAware(true);      XmlPullParser xpp = factory.newPullParser();
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.