1 / 17

안드로이드 앱 프로그래밍 네트워킹

안드로이드 앱 프로그래밍 네트워킹. 2009011049 김준호. 목차. 07-3) 웹으로 요청하기 1. HTTP 프로토콜 2. API 3. 소스코드 예제 4. HTTP CLIENT 클래스 07-4) 뉴스 정보 가져오기 1. RSS 2. DOM, SAX 파서 3. 소스코드 예제. 07-3) 웹으로 요청하기. 1. HTTP 프로토콜. HTTP 프로토콜이란 ? TCP 기반의 웹서비스용 전송규약으로 어플리케이션 계층에서 응용

mercury
Télécharger la présentation

안드로이드 앱 프로그래밍 네트워킹

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 안드로이드앱 프로그래밍네트워킹 2009011049 김준호

  2. 목차 07-3) 웹으로 요청하기 1. HTTP 프로토콜 2. API 3. 소스코드 예제 4. HTTP CLIENT 클래스 07-4) 뉴스 정보 가져오기 1. RSS 2. DOM, SAX 파서 3. 소스코드 예제

  3. 07-3) 웹으로 요청하기 1. HTTP 프로토콜 • HTTP 프로토콜이란? • TCP 기반의 웹서비스용 전송규약으로 어플리케이션 계층에서 응용 • 프로그램의 데이터(텍스트, 그림, 음악, 멀티미디어 등)을 송수신하 • 기 위해 필요한 프로토콜로써 메시지(Message-어플리케이션 계층의 패킷)를기반으로 두고 있다.

  4. 07-3) 웹으로 요청하기 2. API • publicURLConnectionopenConnetion() -생성된 URL 객체의 openConnection() 메소드를호출하여 URLConnection객체 생성 • public void setRequestMethod (String method) -요청 방식을 지정하는 함수 -GET나 POST 문자열을 인자로 전달 • public void setRequestProperty (Stiring field, String newValue) -요청시 헤더에 들어가는 필드 값 지정

  5. 07-3) 웹으로 요청하기 3. 소스코드 예제(XML 레이아웃) //접속 주소를 입력할 입력상자 정의 <EditText android:id="@+id/input01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Enter URL String ..." android:textSize="18dp" > </EditText> //요청 버튼 정의 <Button android:id="@+id/requestBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" 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:id="@+id/txtMsg" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff99ccee" android:textColor="#ff0000ff" android:textSize="12dp“ > </TextView> </ScrollView>

  6. 07-3) 웹으로 요청하기 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 = newStringBuilder(); try { URL url = new URL(urlStr); //URL 객체 생성 HttpURLConnectionconn = (HttpURLConnection)url.openConnection(); //HttpURLConnection객체 생성 …(중략) returnoutput.toString(); } }

  7. 07-3) 웹으로 요청하기 3. 소스코드 예제(메인 액티비티) URL url = new URL(urlStr); HttpURLConnectionconn = (HttpURLConnection)url.openConnection(); if (conn != null){ conn.setConnectTimeout(10000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); intresCode = conn.getResponseCode(); //서버에접속하여 요청 if (resCode == HttpURLConnection.HTTP_OK){ BufferedReader reader = newBufferedReader( //스트림 객체 생성 newInputStreamReader(conn.getInputStream())); while(true){ String line = reader.readLine(); //한 줄씩 읽어 결과 문자열에 추가 if (line == null) break; output.append(line + "\n"); } reader.close(); conn.disconnect(); } returnoutput.toString(); } }

  8. 07-3) 웹으로 요청하기 4. HTTP CLIENT 클래스 1) HttpClient • 웹 서버에 접근하는 가장 기본적인 방식인 HttpURLConnection클래스 객체를 이용하는 방법 외에도 좀 더 다양한 기능을 제공하는 아파치 라이브러리를 이용하기 위해 HttpClient클래스를 사용하면 좋다. 2) 소스예제 try { HttpClient client = newDefaultHttpClient(); //HttpClient객체 생성 HttpPosthttppost = newHttpPost(urlStr); //HttpPost객체 생성 HttpResponse response = client.execute(httppost); //웹페이지 요청 InputStreaminstream = response.getEntity().getContent(); //InputStream객체 참조 BufferedReader reader = newBufferedReader(newInputStreamReader(instream)); }

  9. 07-4) 뉴스 정보 가져오기 1. RSS • RSS란? • 'Really Simple Syndication' 또는 'Rich Site Summary'의 약자로 '매우 풍부한 배급', '풍부한 사이트 요약'이라고 한다.RSS는 전체의 정보가 아닌 헤드라인만을 나열하여 그 중 원하는 정보에 접근할 수 있도록 해주는 서비스로, 온라인상에 콘텐츠를 배열하는 HTML과 이를 전송해주는 이메일 기술의 장점을 가지고 있다.

  10. 07-4) 뉴스 정보 가져오기 2. DOM, SAX 파서 • DOM파서와 SAX파서 란? XML문서를 파싱하기 위해 만들어진 파서들로, DOM파서는 XML 문서 전체를 읽어들인 후 각각의 태그 정보를 사용하는 방식이며 SAX파서는 읽어들인 태그 정보가 있으면 필요한 만큼 부분적으로 처리할 수 있는 방식이다.

  11. 3. 소스코드 예제(메인 액티비티) 07-4) 뉴스 정보 가져오기 public class sampleRSSFeederAvtivityextendsActivity { private static String rss_url = "http://rss.joinsman.com/joins_star_list.xml" …(중략) ArryList<RSSNewsItem> newsItemList; // 리스트 객체 선언 public void onCreate(Bundle savedInstanceState) { …(중략) // 어댑터 객체 선언 list = newRSSListView(this); adapter = newRSSListAdapter(this); list.setAdapter(adapter); // 리스너 설정 list.setOnDataSelectionListener(newOnDataSelectionListener() { public voidonDataSelected(adapterView parent, View v, int position, long id) { String curTitle = curItem.getTitle(); } }); newsItemList = newArrayList<RSSNewsItem>(); LinearLayoutmainLayout = (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(); } } }

  12. 3. 소스코드 예제(하부 액티비티1) 07-4) 뉴스 정보 가져오기 public class sampleRSSFeederAvtivityextends Activity { …(중략) classRefreshThreadextends Thread { …(중략) public void run() { try { //Document Builder 객체 생성 DocumentbuilderFactorybuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); URL urlForHttp = new URL(urlStr); InputStreaminstream = getInputStreamUsingHTTP(urlForHttp); //스트림 객체 참조 Document document = builder.parse(instream); //Document 생성 intcountItem = processDocument(document); //Document 객체 처리 handler.post(updateRSSRunnable); } } } …(중략) }

  13. 3. 소스코드 예제(하부 액티비티2) 07-4) 뉴스 정보 가져오기 public class sampleRSSFeederAvtivityextends Activity { …(중략) private intprocessDocument(Document doc){ newsItemList.clear(); Element docEle = doc.getDocumnetElement(); ModeListnodelist = docEle.getElementsByTagName("item"); // 노드 리스트 확인 int count = 0; if (((nodelist != null) && (nodelist.getLength() > 0)) { for (inti=0; I < nodelist.getLength(); i++) { RSSNewsItemnewsItem = dissectNode(nodelist, i); // RSSNewsItem객체 생성 if(newsItem != null) { newsItemList.add(newsItem); // RSSNewsItem객체 추가 count++; …(중략) return count; } privateRSSNewsItemdissectNode(NodeListnodelist, intindex) { RSSNewsItemnewsItem = 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); NodeListpubDataNode = 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 = newRSSNewsItem(titleValue, linkValue, descriptionValue, pubDateValue, authorValue, categoryValue); } returnnewsItem; }

  14. 3. 소스코드 예제(하부 액티비티2) 07-4) 뉴스 정보 가져오기 …. RunnableupdateRSSRunnable = newRunnable() { public void run() { try { Resources res = getResources(); DrawablerssIcon = res.getDrawable(R.drawable.rss_icon); for (inti=0; i < newsItemList.size(); i++) { RSSNewsItemnewsItem = (RSSNewsItem) newsItemList.get(i); newsItem.setIcon(rssIcon); adapter.addItem(newsItem); // RSSNewsItem객체를 어댑터에 추가 } adapter.notifyDataSetChanged(); // 리스트뷰 업데이트 progressDialog.dismiss(); } catch(Exception ex) { ex.printStackTrace(); } } }; }

  15. Thank you

More Related