본문 바로가기

Android/HttpClient, XmlPullParser

Android HttpClient with XmlPullParser and Google Weather API

안드로이드에서 HttpClient, XmlPullParser를 이용하여 Google Weather API에서 날씨를 가져와서 파싱하는 예

현재의 날씨 중에서 풍향, 풍속만을 추출하여 TextView에 출력하는 내용

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ScrollView android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="match_parent" android:text="TextView" /> </ScrollView> </LinearLayout>


MainActivity.java

package com.example.androidapp; import java.io.*; 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.app.*; import android.os.*; import android.util.*; import android.widget.*; public class MainActivity extends Activity { TextView tv; Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.textView1); 

/* 네트워크 연결 및 요청, 응답은 유저 쓰레드에서 이루어지도록 해야 한다(강제규정) */ new Thread() { public void run() { connect(); } }.start(); } String wind_condition; private void connect() { try{ HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.google.co.kr/ig/api?weather=seoul,korea"); HttpResponse response = httpClient.execute(httpGet); InputStream is = response.getEntity().getContent(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser parser = factory.newPullParser(); parser.setInput(is, "euc-kr"); int eventType = parser.getEventType(); String tagName = null; while(eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_TAG) { tagName = parser.getName(); Log.e("태그이름", tagName); if(tagName.equals("wind_condition")) { wind_condition = parser.getAttributeValue(0);

/* 화면의 갱신은 반드시 메인 쓰레드에서 수행해야 하므로 메인 쓰레드에게 Runnable 객체를 전달한다 */ handler.post(new Runnable() { public void run() { tv.setText(wind_condition); } }); break; } } eventType = parser.next(); } // end of while() }catch(Exception ex) { ex.printStackTrace(); Log.e("접속오류", ex.toString()); } } }


Google Weather API에서 제공하는 날씨정보

<?xml version="1.0"?>

<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<forecast_information>
<city data="seoul,korea"/>
<postal_code data="seoul,korea"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2012-08-21"/>
<current_date_time data="1970-01-01 00:00:00 +0000"/>
<unit_system data="SI"/>
</forecast_information>
<current_conditions>
<condition data="이슬비"/>
<temp_f data="77"/>
<temp_c data="25"/>
<humidity data="습도: 83%"/>
<icon data="/ig/images/weather/mist.gif"/>
<wind_condition data="바람: 남풍, 19 km/h"/>
</current_conditions>
<forecast_conditions>
<day_of_week data=""/>
<low data="22"/>
<high data="28"/>
<icon data="/ig/images/weather/thunderstorm.gif"/>
<condition data="강우(천둥, 번개 동반)"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data=""/>
<low data="21"/>
<high data="25"/>
<icon data="/ig/images/weather/thunderstorm.gif"/>
<condition data="강우(천둥, 번개 동반)"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data=""/>
<low data="18"/>
<high data="27"/>
<icon data="/ig/images/weather/chance_of_storm.gif"/>
<condition data="한때 비바람"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data=""/>
<low data="21"/>
<high data="26"/>
<icon data="/ig/images/weather/chance_of_storm.gif"/>
<condition data="한때 비바람"/>
</forecast_conditions>
</weather>
</xml_api_reply>