Download presentation
1
안드로이드 앱 프로그래밍 네트워킹 김준호
2
07-3) 웹으로 요청하기 07-4) 뉴스 정보 가져오기 목차 1. HTTP 프로토콜 2. API 3. 소스코드 예제
4. HTTP CLIENT 클래스 07-4) 뉴스 정보 가져오기 1. RSS 2. DOM, SAX 파서
3
07-3) 웹으로 요청하기
4
1. HTTP 프로토콜 HTTP 프로토콜이란? TCP 기반의 웹서비스용 전송규약으로 어플리케이션 계층에서 응용
07-3) 웹으로 요청하기 1. HTTP 프로토콜 HTTP 프로토콜이란? TCP 기반의 웹서비스용 전송규약으로 어플리케이션 계층에서 응용 프로그램의 데이터(텍스트, 그림, 음악, 멀티미디어 등)을 송수신하 기 위해 필요한 프로토콜로써 메시지(Message-어플리케이션 계층의 패킷)를 기반으로 두고 있다.
5
07-3) 웹으로 요청하기 2. API public URLConnection openConnetion() -생성된 URL 객체의 openConnection() 메소드를 호출하여 URLConnection 객체 생성 public void setRequestMethod (String method) -요청 방식을 지정하는 함수 -GET나 POST 문자열을 인자로 전달 public void setRequestProperty (Stiring field, String newValue) -요청시 헤더에 들어가는 필드 값 지정 Get? Post? Field newvalue?
6
3. 소스코드 예제(XML 레이아웃) 07-3) 웹으로 요청하기 //접속 주소를 입력할 입력상자 정의 <EditText
android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Enter URL String ..." android:textSize="18dp" > </EditText> //요청 버튼 정의 <Button android:text="Request" android:textSize="20dp" android:textStyle="bold" > </Button> //텍스트뷰에 스크롤 기능을 추가하기 위한 스크롤뷰 정의 <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp"> //결과물을 보여줄 텍스트뷰 정의 <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff99ccee" android:textColor="#ff0000ff" android:textSize="12dp“ > </TextView> </ScrollView>
7
3. 소스코드 예제(메인 액티비티) 07-3) 웹으로 요청하기
requestBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { String urlStr = input01.getText().toString(); //URL 문자열 참조 String output = request(urlStr); //request() 메소드 호출 txtMsg.setText(output); //결과물 표시 } }); Private String request(String urlStr) { StringBuilder output = new StringBuilder(); try { URL url = new URL(urlStr); //URL 객체 생성 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //HttpURLConnection 객체 생성 …(중략) return output.toString();
8
3. 소스코드 예제(메인 액티비티) 07-3) 웹으로 요청하기 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())); while(true){ String line = reader.readLine(); //한 줄씩 읽어 결과 문자열에 추가 if (line == null) break; output.append(line + "\n"); } reader.close(); conn.disconnect(); return output.toString();
9
4. HTTP CLIENT 클래스 1) HttpClient 2) 소스예제
07-3) 웹으로 요청하기 4. HTTP CLIENT 클래스 1) HttpClient 웹 서버에 접근하는 가장 기본적인 방식인 HttpURLConnection 클래스 객체를 이용하는 방법 외에도 좀 더 다양한 기능을 제공하는 아파치 라이브러리를 이용하기 위해 HttpClient 클래스를 사용하면 좋다. 2) 소스예제 try { HttpClient client = new DefaultHttpClient(); //HttpClient 객체 생성 HttpPost httppost = new HttpPost(urlStr); //HttpPost 객체 생성 HttpResponse response = client.execute(httppost); //웹페이지 요청 InputStream instream = response.getEntity().getContent(); //InputStream 객체 참조 BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); }
10
07-4) 뉴스 정보 가져오기
11
07-4) 뉴스 정보 가져오기 1. RSS RSS란? 'Really Simple Syndication' 또는 'Rich Site Summary'의 약자로 '매우 풍부한 배급', '풍부한 사이트 요약'이라고 한다. RSS는 전체의 정보가 아닌 헤드라인만을 나열하여 그 중 원하는 정보에 접근할 수 있도록 해주는 서비스로, 온라인상에 콘텐츠를 배열하는 HTML과 이를 전송해주는 이메일 기술의 장점을 가지고 있다.
12
07-4) 뉴스 정보 가져오기 2. DOM, SAX 파서 DOM파서와 SAX파서 란? XML문서를 파싱하기 위해 만들어진 파서들로, DOM파서는 XML 문서 전체를 읽어들인 후 각각의 태그 정보를 사용하는 방식이며 SAX파서는 읽어들인 태그 정보가 있으면 필요한 만큼 부분적으로 처리할 수 있는 방식이다. 문서의 양이 많거나 내용이 순차적으로 구성된 경우에는 빠른 처리가 가능한 SAX 파서를 많이 사용한다. 작은 용량의 문서를 구조화하여 처리하는 데는 DOM파서가 더 직관적이고 간단할 수 있다. Document, element, attribute 노드
13
3. 소스코드 예제(메인 액티비티) 07-4) 뉴스 정보 가져오기
public class sampleRSSFeederAvtivity extends Activity { private static String rss_url = " …(중략) ArryList<RSSNewsItem> newsItemList; // 리스트 객체 선언 public void onCreate(Bundle savedInstanceState) { // 어댑터 객체 선언 list = new RSSListView(this); adapter = new RSSListAdapter(this); list.setAdapter(adapter); // 리스너 설정 list.setOnDataSelectionListener(new OnDataSelectionListener() { public void onDataSelected(adapterView parent, View v, int position, long id) { String curTitle = curItem.getTitle(); } }); newsItemList = new ArrayList<RSSNewsItem>(); LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout); mainLayout.addView(list, params); show_btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { String inputStr = edit01.getText().toString(); showRSS(inputStr); // 메소드 호출 // 스레드 시작 private void showRSS(String urlStr) { try { RefreshThread thread = new RefreshThread(urlStr); thread.start();
14
3. 소스코드 예제(하부 액티비티1) 07-4) 뉴스 정보 가져오기
public class sampleRSSFeederAvtivity extends Activity { …(중략) class RefreshThread extends Thread { public void run() { try { //Document Builder 객체 생성 DocumentbuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); URL urlForHttp = new URL(urlStr); InputStream instream = getInputStreamUsingHTTP(urlForHttp); //스트림 객체 참조 Document document = builder.parse(instream); //Document 생성 int countItem = processDocument(document); //Document 객체 처리 handler.post(updateRSSRunnable); }
15
3. 소스코드 예제(하부 액티비티2) 07-4) 뉴스 정보 가져오기
public class sampleRSSFeederAvtivity extends Activity { …(중략) private int processDocument(Document doc){ newsItemList.clear(); Element docEle = doc.getDocumnetElement(); ModeList nodelist = docEle.getElementsByTagName("item"); // 노드 리스트 확인 int count = 0; if (((nodelist != null) && (nodelist.getLength() > 0)) { for (int i=0; I < nodelist.getLength(); i++) { RSSNewsItem newsItem = dissectNode(nodelist, i); // RSSNewsItem 객체 생성 if(newsItem != null) { newsItemList.add(newsItem); // RSSNewsItem 객체 추가 count++; return count; } private RSSNewsItem dissectNode(NodeList nodelist, int index) { RSSNewsItem newsItem = null; try { Element entry = (Element) nodelist.item(index); // 현재 Element 객체 참조 Element title = (Element) entry.getElementsByTagName("title").item(0); Element link = (Element) entry.getElementsByTagName("link").item(0); Element description = (Element) entry.getElementsByTagName("description").item(0); NodeList pubDataNode = entry.getElementsByTagName("pubData"); if (pubDataNode == null) pubDataNode = entry.getElementsByTagName("dc:data"); Element pubData = (Element) pubDataNode.item(0); Element author = (Element) entry.getElementsByTagName("author").item(0); Element category = (Element) entry.getElementsByTagName("category").item(0); String titleValue = null; if (title != null) titleValue = title.getFirstChild().getNodeValue(); // RSSNewsItem 객체 생성 newsItem = new RSSNewsItem(titleValue, linkValue, descriptionValue, pubDateValue, authorValue, categoryValue); return newsItem;
16
3. 소스코드 예제(하부 액티비티2) 07-4) 뉴스 정보 가져오기 ….
Runnable updateRSSRunnable = new Runnable() { public void run() { try { Resources res = getResources(); Drawable rssIcon = res.getDrawable(R.drawable.rss_icon); for (int i=0; i < newsItemList.size(); i++) { RSSNewsItem newsItem = (RSSNewsItem) newsItemList.get(i); newsItem.setIcon(rssIcon); adapter.addItem(newsItem); // RSSNewsItem 객체를 어댑터에 추가 } adapter.notifyDataSetChanged(); // 리스트뷰 업데이트 progressDialog.dismiss(); } catch(Exception ex) { ex.printStackTrace(); };
17
Thank you 문서의 양이 많거나 내용이 순차적으로 구성된 경우에는 빠른 처리가 가능한 SAX 파서를 많이 사용한다.
작은 용량의 문서를 구조화하여 처리하는 데는 DOM파서가 더 직관적이고 간단할 수 있다. Document, element, attribute 노드
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.