안드로이드에서 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"></xml_api_reply>