SlideShare una empresa de Scribd logo
1 de 7
Android XML Parsing

S.O.LAB Develop by Oracleon
웹 요청1
Http 클라이언트 만들기
 1. URL 객체 생성
 2. openConnection() 메소드 호출
 3. HttpURLConnection 객체형으로 casting 후 데이터 교환

URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if (conn != null) {
          conn.setConnectTimeout(10000);
          conn.setRequestMethod("GET");
          conn.setDoInput(true);
          conn.setDoOutput(true);

         int resCode = conn.getResponseCode();
         if (resCode == HttpURLConnection.HTTP_OK) {
             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())) ;
             String line = null;
             while(true) {
               line = reader.readLine();
               if (line == null) {
                   break;
               }
               output.append(line + "n");
             }
             reader.close();
             conn.disconnect();
         }
웹 요청1

 메소드 설명

1. setRequestMethod(“GET”) // Get방식 요청설정
2. setDoInput(),setDoOutput() // 객체의 입출력이 가능하로록 설정
3. getResposeCode() // 이시점에 웹서버에 페이지 요청시작
4. 응답코드 HTTP_OK : 정상 / HTTP_NOT_FOUND :페이지없음
5. readLine()은 BufferedReader클래스에 정의되어 있다.
6. HttpURLConnection객체인 conn을 InputStreamReaderr객체로 만든후
  BufferedReader 클래스형 객체로 만든다.

BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream())) ;
String line = reader.readLine();
DOM Parser
DOM : 트리형식으로 전체구조 파악후 정보 추출,메모리 사용높음, 고성능
SAX : 순차적으로 문서를 읽으면서 차례대로 추출, 메모리 사용낮음, 느림


 import javax.xml.parsers.*;
 import org.w3c.dom.*;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8"));
Document doc = builder.parse(istream);

Element order = doc.getDocumentElement();
NodeList items = order.getElementsByTagName("item");
Node item = items.item(0);
Node text = item.getFirstChild();
String ItemName = text.getNodeValue();
mResult.setText("주문 항목 : " + ItemName);
DOM Parser
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- 추상클래스이므로 직접생성할수 없고 newInstace 정적메소드로 생성한다.

DocumentBuilder builder = factory.newDocumentBuilder();
실제파싱을 할 builder 객체도 정적메소드 newDocumnetBuilder() 로 생성한다.

 String xml = "<?xml version="1.0" encoding="utf-8"?>n" +
 "<order><item>Mouse</item></order>";

InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8"));
Document doc = builder.parse(istream);
parse메소드는 스트림을 분석하여 메모리에 트리형태로 전개해 놓는다.
이후 Document객체의 메소드를 이용하여 요소들을 빨리 읽을수 있다.

Element order = doc.getDocumentElement();
NodeList items = order.getElementsByTagName("item");
Node item = items.item(0);
Node text = item.getFirstChild();
String ItemName = text.getNodeValue();
DOM Parser
    String xml = "<?xml version="1.0" encoding="utf-8"?>n" +
    "<order>" +
    "<item Maker="Samsung" Price="23000">Mouse</item>" +
    "<item Maker="LG" Price="12000">KeyBoard</item>" +
    "<item Price="156000" Maker="Western Digital">HDD</item>" +
    "</order>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8"));
Document doc = builder.parse(istream);

Element order = doc.getDocumentElement();
NodeList items = order.getElementsByTagName("item");
String Result = "";
for (int i = 0; i < items.getLength();i++) {
                Node item = items.item(i);
                Node text = item.getFirstChild();
                String ItemName = text.getNodeValue();
                Result += ItemName + " : ";

              NamedNodeMap Attrs = item.getAttributes();
              for (int j = 0;j < Attrs.getLength(); j++) {
                              Node attr = Attrs.item(j);
                              Result += (attr.getNodeName() + " = " + attr.getNodeValue() + " ");
                              }
                              Result += "n";
              }
              mResult.setText("주문 목록n" + Result);
}
SAX parse
Http 클라이언트 만들기
1. URL 객체 생성
2. openConnection() 메소드 호출
3. HttpURLConnection 객체형으로 casting 후 데이터 교환

Más contenido relacionado

La actualidad más candente

옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개beom kyun choi
 
엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나종민 김
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storageJinKyoungHeo
 
Redis data design by usecase
Redis data design by usecaseRedis data design by usecase
Redis data design by usecaseKris Jeong
 
데이터베이스패턴
데이터베이스패턴데이터베이스패턴
데이터베이스패턴Suan Lee
 
Undertow RequestBufferingHandler 소개
Undertow RequestBufferingHandler 소개Undertow RequestBufferingHandler 소개
Undertow RequestBufferingHandler 소개Ted Won
 
JSP 프로그래밍 #05 HTML과 JSP
JSP 프로그래밍 #05 HTML과 JSPJSP 프로그래밍 #05 HTML과 JSP
JSP 프로그래밍 #05 HTML과 JSPMyungjin Lee
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivityJinKyoungHeo
 
파이썬 웹프로그래밍 1탄
파이썬 웹프로그래밍 1탄 파이썬 웹프로그래밍 1탄
파이썬 웹프로그래밍 1탄 SeongHyun Ahn
 
Apache solr소개 20120629
Apache solr소개 20120629Apache solr소개 20120629
Apache solr소개 20120629Dosang Yoon
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]MongoDB
 
Block chain introduction slideshare
Block chain introduction   slideshareBlock chain introduction   slideshare
Block chain introduction slidesharewonyong hwang
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄SeongHyun Ahn
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발Jay JH Park
 
파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄SeongHyun Ahn
 
Ajax ellen seon_ss
Ajax ellen seon_ssAjax ellen seon_ss
Ajax ellen seon_ssEllen Seon
 

La actualidad más candente (20)

Gcm
GcmGcm
Gcm
 
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
 
JSON with C++ & C#
JSON with C++ & C#JSON with C++ & C#
JSON with C++ & C#
 
엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나
 
Rapid json tutorial
Rapid json tutorialRapid json tutorial
Rapid json tutorial
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storage
 
Redis data design by usecase
Redis data design by usecaseRedis data design by usecase
Redis data design by usecase
 
데이터베이스패턴
데이터베이스패턴데이터베이스패턴
데이터베이스패턴
 
Undertow RequestBufferingHandler 소개
Undertow RequestBufferingHandler 소개Undertow RequestBufferingHandler 소개
Undertow RequestBufferingHandler 소개
 
JSP 프로그래밍 #05 HTML과 JSP
JSP 프로그래밍 #05 HTML과 JSPJSP 프로그래밍 #05 HTML과 JSP
JSP 프로그래밍 #05 HTML과 JSP
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivity
 
파이썬 웹프로그래밍 1탄
파이썬 웹프로그래밍 1탄 파이썬 웹프로그래밍 1탄
파이썬 웹프로그래밍 1탄
 
Apache solr소개 20120629
Apache solr소개 20120629Apache solr소개 20120629
Apache solr소개 20120629
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
 
Block chain introduction slideshare
Block chain introduction   slideshareBlock chain introduction   slideshare
Block chain introduction slideshare
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발
 
4-2. ajax
4-2. ajax4-2. ajax
4-2. ajax
 
파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄
 
Ajax ellen seon_ss
Ajax ellen seon_ssAjax ellen seon_ss
Ajax ellen seon_ss
 

Destacado

Prakt.jarkom2 jefri tugas4 ospf multi area
Prakt.jarkom2 jefri tugas4 ospf multi areaPrakt.jarkom2 jefri tugas4 ospf multi area
Prakt.jarkom2 jefri tugas4 ospf multi areaJefri Fahrian
 
Stefan Larsson CEO, keynote on BIMobject live 2014
Stefan Larsson CEO, keynote on BIMobject live 2014Stefan Larsson CEO, keynote on BIMobject live 2014
Stefan Larsson CEO, keynote on BIMobject live 2014BIMobject
 
Utah's Tort of Wrongful Termination in Violation of Public Policy
Utah's Tort of Wrongful Termination in Violation of Public PolicyUtah's Tort of Wrongful Termination in Violation of Public Policy
Utah's Tort of Wrongful Termination in Violation of Public PolicyParsons Behle & Latimer
 
BISO Time Attendance Software Report Presentation
BISO Time Attendance Software Report PresentationBISO Time Attendance Software Report Presentation
BISO Time Attendance Software Report PresentationBISO Developments
 
EN3604 Week 5: "No Surrender"?" Conflicts within and Beyond
EN3604 Week 5: "No Surrender"?" Conflicts within and BeyondEN3604 Week 5: "No Surrender"?" Conflicts within and Beyond
EN3604 Week 5: "No Surrender"?" Conflicts within and BeyondClaire Lynch
 
Paper3 jefri common errors
Paper3 jefri common errorsPaper3 jefri common errors
Paper3 jefri common errorsJefri Fahrian
 
Recent Developments in Employee Background Checks
Recent Developments in Employee Background ChecksRecent Developments in Employee Background Checks
Recent Developments in Employee Background ChecksParsons Behle & Latimer
 
Летни гуми - инфо
Летни гуми - инфоЛетни гуми - инфо
Летни гуми - инфоMartin Patzekov
 
Corporate Profile - Prosols Technology
Corporate Profile - Prosols TechnologyCorporate Profile - Prosols Technology
Corporate Profile - Prosols Technologypraveen21212
 
Microsoft word mengurus perubahan
Microsoft word   mengurus perubahanMicrosoft word   mengurus perubahan
Microsoft word mengurus perubahanFaizzah Izam
 

Destacado (18)

Prakt.jarkom2 jefri tugas4 ospf multi area
Prakt.jarkom2 jefri tugas4 ospf multi areaPrakt.jarkom2 jefri tugas4 ospf multi area
Prakt.jarkom2 jefri tugas4 ospf multi area
 
Tizen web app
Tizen web appTizen web app
Tizen web app
 
5 regnes
5 regnes5 regnes
5 regnes
 
Stefan Larsson CEO, keynote on BIMobject live 2014
Stefan Larsson CEO, keynote on BIMobject live 2014Stefan Larsson CEO, keynote on BIMobject live 2014
Stefan Larsson CEO, keynote on BIMobject live 2014
 
Utah's Tort of Wrongful Termination in Violation of Public Policy
Utah's Tort of Wrongful Termination in Violation of Public PolicyUtah's Tort of Wrongful Termination in Violation of Public Policy
Utah's Tort of Wrongful Termination in Violation of Public Policy
 
BISO Time Attendance Software Report Presentation
BISO Time Attendance Software Report PresentationBISO Time Attendance Software Report Presentation
BISO Time Attendance Software Report Presentation
 
EN3604 Week 5: "No Surrender"?" Conflicts within and Beyond
EN3604 Week 5: "No Surrender"?" Conflicts within and BeyondEN3604 Week 5: "No Surrender"?" Conflicts within and Beyond
EN3604 Week 5: "No Surrender"?" Conflicts within and Beyond
 
Paper3 jefri common errors
Paper3 jefri common errorsPaper3 jefri common errors
Paper3 jefri common errors
 
Recent Developments in Employee Background Checks
Recent Developments in Employee Background ChecksRecent Developments in Employee Background Checks
Recent Developments in Employee Background Checks
 
нам год
нам годнам год
нам год
 
Летни гуми - инфо
Летни гуми - инфоЛетни гуми - инфо
Летни гуми - инфо
 
Cijferend optellen2
Cijferend optellen2Cijferend optellen2
Cijferend optellen2
 
Sena
SenaSena
Sena
 
Employment Compliance Audits
Employment Compliance AuditsEmployment Compliance Audits
Employment Compliance Audits
 
Corporate Profile - Prosols Technology
Corporate Profile - Prosols TechnologyCorporate Profile - Prosols Technology
Corporate Profile - Prosols Technology
 
Microsoft word mengurus perubahan
Microsoft word   mengurus perubahanMicrosoft word   mengurus perubahan
Microsoft word mengurus perubahan
 
photo onlt presentation
photo onlt presentationphoto onlt presentation
photo onlt presentation
 
Diana vela
Diana velaDiana vela
Diana vela
 

Similar a Android xml parsing

C# Game Server
C# Game ServerC# Game Server
C# Game Serverlactrious
 
JSP 프로그래밍 #03 서블릿
JSP 프로그래밍 #03 서블릿JSP 프로그래밍 #03 서블릿
JSP 프로그래밍 #03 서블릿Myungjin Lee
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GDG Korea
 
Node.js and react
Node.js and reactNode.js and react
Node.js and reactHyungKuIm
 
[Study]HeadFirst JSP&servlet chapter5
[Study]HeadFirst JSP&servlet chapter5[Study]HeadFirst JSP&servlet chapter5
[Study]HeadFirst JSP&servlet chapter5Hyeonseok Yang
 
Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Sangon Lee
 
Do IoT Yourself! - 사물 간의 연결을 위한 Open API
Do IoT Yourself! - 사물 간의 연결을 위한 Open APIDo IoT Yourself! - 사물 간의 연결을 위한 Open API
Do IoT Yourself! - 사물 간의 연결을 위한 Open APIHyunghun Cho
 
Java advancd ed10
Java advancd ed10Java advancd ed10
Java advancd ed10hungrok
 
HeadFisrt Servlet&JSP Chapter 2
HeadFisrt Servlet&JSP Chapter 2HeadFisrt Servlet&JSP Chapter 2
HeadFisrt Servlet&JSP Chapter 2J B
 
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationSecrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationHyuncheol Jeon
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.jsWoo Jin Kim
 
Dom 생성과정
Dom 생성과정Dom 생성과정
Dom 생성과정abapier
 
Android Network
Android NetworkAndroid Network
Android Networkcooddy
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&httpDong Jun Kwon
 
overview of spring4
overview of spring4overview of spring4
overview of spring4Arawn Park
 

Similar a Android xml parsing (20)

C# Game Server
C# Game ServerC# Game Server
C# Game Server
 
JSP 프로그래밍 #03 서블릿
JSP 프로그래밍 #03 서블릿JSP 프로그래밍 #03 서블릿
JSP 프로그래밍 #03 서블릿
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
[Study]HeadFirst JSP&servlet chapter5
[Study]HeadFirst JSP&servlet chapter5[Study]HeadFirst JSP&servlet chapter5
[Study]HeadFirst JSP&servlet chapter5
 
Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조
 
Do IoT Yourself! - 사물 간의 연결을 위한 Open API
Do IoT Yourself! - 사물 간의 연결을 위한 Open APIDo IoT Yourself! - 사물 간의 연결을 위한 Open API
Do IoT Yourself! - 사물 간의 연결을 위한 Open API
 
Java advancd ed10
Java advancd ed10Java advancd ed10
Java advancd ed10
 
Spring boot actuator
Spring boot   actuatorSpring boot   actuator
Spring boot actuator
 
HeadFisrt Servlet&JSP Chapter 2
HeadFisrt Servlet&JSP Chapter 2HeadFisrt Servlet&JSP Chapter 2
HeadFisrt Servlet&JSP Chapter 2
 
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationSecrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
 
10주 ajax
10주 ajax10주 ajax
10주 ajax
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.js
 
[Codelab 2017] ReactJS 기초
[Codelab 2017] ReactJS 기초[Codelab 2017] ReactJS 기초
[Codelab 2017] ReactJS 기초
 
Dom 생성과정
Dom 생성과정Dom 생성과정
Dom 생성과정
 
Spring portfolio2
Spring portfolio2Spring portfolio2
Spring portfolio2
 
Android Network
Android NetworkAndroid Network
Android Network
 
Nodejs_chapter3
Nodejs_chapter3Nodejs_chapter3
Nodejs_chapter3
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&http
 
overview of spring4
overview of spring4overview of spring4
overview of spring4
 

Más de Sangon Lee

NoSQL Guide & Sample
NoSQL Guide &  SampleNoSQL Guide &  Sample
NoSQL Guide & SampleSangon Lee
 
Android ndk jni 설치및 연동
Android ndk jni 설치및 연동Android ndk jni 설치및 연동
Android ndk jni 설치및 연동Sangon Lee
 
번역돋보기 기획서
번역돋보기 기획서번역돋보기 기획서
번역돋보기 기획서Sangon Lee
 
Storyboard iOS 개발실습예제
Storyboard iOS 개발실습예제Storyboard iOS 개발실습예제
Storyboard iOS 개발실습예제Sangon Lee
 
17. cocos2d 기초
17. cocos2d  기초17. cocos2d  기초
17. cocos2d 기초Sangon Lee
 

Más de Sangon Lee (8)

NoSQL Guide & Sample
NoSQL Guide &  SampleNoSQL Guide &  Sample
NoSQL Guide & Sample
 
Gcd ppt
Gcd pptGcd ppt
Gcd ppt
 
Android ndk jni 설치및 연동
Android ndk jni 설치및 연동Android ndk jni 설치및 연동
Android ndk jni 설치및 연동
 
Facebook api
Facebook apiFacebook api
Facebook api
 
번역돋보기 기획서
번역돋보기 기획서번역돋보기 기획서
번역돋보기 기획서
 
StudyShare
StudyShareStudyShare
StudyShare
 
Storyboard iOS 개발실습예제
Storyboard iOS 개발실습예제Storyboard iOS 개발실습예제
Storyboard iOS 개발실습예제
 
17. cocos2d 기초
17. cocos2d  기초17. cocos2d  기초
17. cocos2d 기초
 

Android xml parsing

  • 1. Android XML Parsing S.O.LAB Develop by Oracleon
  • 2. 웹 요청1 Http 클라이언트 만들기 1. URL 객체 생성 2. openConnection() 메소드 호출 3. HttpURLConnection 객체형으로 casting 후 데이터 교환 URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); if (conn != null) { conn.setConnectTimeout(10000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); int resCode = conn.getResponseCode(); if (resCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())) ; String line = null; while(true) { line = reader.readLine(); if (line == null) { break; } output.append(line + "n"); } reader.close(); conn.disconnect(); }
  • 3. 웹 요청1 메소드 설명 1. setRequestMethod(“GET”) // Get방식 요청설정 2. setDoInput(),setDoOutput() // 객체의 입출력이 가능하로록 설정 3. getResposeCode() // 이시점에 웹서버에 페이지 요청시작 4. 응답코드 HTTP_OK : 정상 / HTTP_NOT_FOUND :페이지없음 5. readLine()은 BufferedReader클래스에 정의되어 있다. 6. HttpURLConnection객체인 conn을 InputStreamReaderr객체로 만든후 BufferedReader 클래스형 객체로 만든다. BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())) ; String line = reader.readLine();
  • 4. DOM Parser DOM : 트리형식으로 전체구조 파악후 정보 추출,메모리 사용높음, 고성능 SAX : 순차적으로 문서를 읽으면서 차례대로 추출, 메모리 사용낮음, 느림 import javax.xml.parsers.*; import org.w3c.dom.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8")); Document doc = builder.parse(istream); Element order = doc.getDocumentElement(); NodeList items = order.getElementsByTagName("item"); Node item = items.item(0); Node text = item.getFirstChild(); String ItemName = text.getNodeValue(); mResult.setText("주문 항목 : " + ItemName);
  • 5. DOM Parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - 추상클래스이므로 직접생성할수 없고 newInstace 정적메소드로 생성한다. DocumentBuilder builder = factory.newDocumentBuilder(); 실제파싱을 할 builder 객체도 정적메소드 newDocumnetBuilder() 로 생성한다. String xml = "<?xml version="1.0" encoding="utf-8"?>n" + "<order><item>Mouse</item></order>"; InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8")); Document doc = builder.parse(istream); parse메소드는 스트림을 분석하여 메모리에 트리형태로 전개해 놓는다. 이후 Document객체의 메소드를 이용하여 요소들을 빨리 읽을수 있다. Element order = doc.getDocumentElement(); NodeList items = order.getElementsByTagName("item"); Node item = items.item(0); Node text = item.getFirstChild(); String ItemName = text.getNodeValue();
  • 6. DOM Parser String xml = "<?xml version="1.0" encoding="utf-8"?>n" + "<order>" + "<item Maker="Samsung" Price="23000">Mouse</item>" + "<item Maker="LG" Price="12000">KeyBoard</item>" + "<item Price="156000" Maker="Western Digital">HDD</item>" + "</order>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream istream = new ByteArrayInputStream(xml.getBytes("utf-8")); Document doc = builder.parse(istream); Element order = doc.getDocumentElement(); NodeList items = order.getElementsByTagName("item"); String Result = ""; for (int i = 0; i < items.getLength();i++) { Node item = items.item(i); Node text = item.getFirstChild(); String ItemName = text.getNodeValue(); Result += ItemName + " : "; NamedNodeMap Attrs = item.getAttributes(); for (int j = 0;j < Attrs.getLength(); j++) { Node attr = Attrs.item(j); Result += (attr.getNodeName() + " = " + attr.getNodeValue() + " "); } Result += "n"; } mResult.setText("주문 목록n" + Result); }
  • 7. SAX parse Http 클라이언트 만들기 1. URL 객체 생성 2. openConnection() 메소드 호출 3. HttpURLConnection 객체형으로 casting 후 데이터 교환