본문 바로가기

Android/HttpClient & XmlPullParser

Android HttpClient with XmlPullParser example

res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >


        <TextView

       android:id="@+id/textView1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignParentTop="true"

       android:layout_centerHorizontal="true"

       android:layout_marginTop="68dp"

       android:text="TextView" />


</RelativeLayout>



fruits.jsp


<?xml version="1.0" encoding="EUC-KR" ?>

<%@ page contentType="text/xml; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<fruits>

<fruit num="1">

<name>오렌지</name>

<price>2000</price>

</fruit>

<fruit num="2">

<name>Melon</name>

<price>3000</price>

</fruit>

<fruit num="3">

<name>Apple</name>

<price>4000</price>

</fruit>

</fruits>



MainActivity.java


package com.example.androidtest;


import java.io.*;

import java.net.Socket;


import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.xmlpull.v1.XmlPullParser;

import org.xmlpull.v1.XmlPullParserFactory;


import android.os.*;

import android.util.Log;

import android.view.View;

import android.widget.*;

import android.app.*;


public class MainActivity extends Activity {


TextView tv;

StringBuilder strBuilder = new StringBuilder();

// 메인 쓰레드와 자동으로 연결되는 메시지 핸들러

Handler handler = new Handler();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

   tv = (TextView) findViewById(R.id.textView1); 

        // 안드로이드에서 네트워크 접속, 요청, 응답의 처리는 유저 쓰레드 내에서 이루어져야 한다 (강제규정)

        new Thread() {

        public void run() {

        connect();

        }

        }.start();

}


private void connect() {

    try{ 

    HttpClient httpClient = new DefaultHttpClient();

    HttpGet httpGet = new HttpGet("http://203.233.196.3:8080/MyWeb/fruits.jsp");

    HttpResponse response = httpClient.execute(httpGet);

   

InputStream is = response.getEntity().getContent();

InputStreamReader isr = new InputStreamReader(is, "EUC-KR");

BufferedReader br = new BufferedReader(isr);

String line = null;

while((line=br.readLine())!=null) {

strBuilder.append(line+"\n");

}

br.close();

// XML 파서를 이용하여 XML포맷으로 전달된 데이터에서 필요한 내용만 추출하여

// 화면에 출력한다

findName(strBuilder.toString());


    }catch(Exception ex) {

    ex.printStackTrace();

    Log.e("접속오류", ex.toString());

    }

    }

    String fruitName, priceValue;

    private void findName(String xmlString) {


    try {

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

factory.setNamespaceAware(true);

XmlPullParser xpp = factory.newPullParser();

xpp.setInput( new StringReader ( xmlString));

int eventType = xpp.getEventType();


       while (eventType != XmlPullParser.END_DOCUMENT) {

           if(eventType == XmlPullParser.START_DOCUMENT) {

            Log.i("Start document","시작태그");

           } else if(eventType == XmlPullParser.START_TAG) {

            Log.i("Start tag", ""+xpp.getName());

            String tagName = xpp.getName();


            if(tagName.equals("fruit")) {

            String num = xpp.getAttributeValue(0);

            Log.i("속성 값", num);

            }


            int cnt = xpp.getAttributeCount();

            if(cnt != -1) {

            for(int i=0;i<cnt;i++) {

            if(xpp.getAttributeName(i).equals("num")) {

            if(xpp.getAttributeValue(0).equals("1")) {

            //Log.i("찾음", "1번");

            xpp.next(); // empty TEXT

            xpp.next(); // name element

            xpp.next(); // TEXT(오렌지)

            fruitName = xpp.getText(); // 오렌지

            xpp.next(); // </name>

            xpp.next(); // empty TEXT

            xpp.next(); // price element

            xpp.next(); // 2000

            priceValue = xpp.getText();

            Log.i(fruitName, priceValue); 

                                                 //  유저 쓰레드 내에서 화면을 갱신할 수 없으므로 메인 쓰레드에게 전달하여 실행하도록 한다

            handler.post(new Runnable() {

                public void run() {

                tv.setText(fruitName+":"+priceValue);

                }

                });

            }

            }

            }

            }

           } else if(eventType == XmlPullParser.END_TAG) {

            Log.i("End tag", ""+xpp.getName());

           } else if(eventType == XmlPullParser.TEXT) {

               Log.i("TEXT", ""+xpp.getText());

           }

           eventType = xpp.next();

       }

} catch (Exception e) {

Log.e("오류", ""+e.getMessage());

}

    Log.e("종료", "프로그램 종료");

    }

}