안드로이드에서 HttpClient를 이용하여 Google Weather API에 접속하고 날씨 정보를 가져오는 예
Google Weather API 에서 제공하는 날씨정보는 XML 포맷으로 전달되므로 일단 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>
res/layout/main.xml
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 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(); } StringBuilder strBuilder = new StringBuilder(); 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(); 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(); handler.post(new Runnable() { public void run() { tv.setText(strBuilder.toString()); } }); }catch(Exception ex) { ex.printStackTrace(); Log.e("접속오류", ex.toString()); } } }
Google Weather API가 제공하는 날씨정보
<?xml version="1.0"?>
<xml_api_reply version="1"></xml_api_reply>