본문 바로가기

Android/Seoul OpenAPI 01

Android Seoul OpenAPI example

안드로이드에서 서울 OpenAPI를 이용하여 데이터를 가져와서 출력하는 예

서울안심먹거리 목록 중에서 50개 항목을 가져와서 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="wrap_content" android:text="분실물 검색" /> </ScrollView> </LinearLayout>

AndroidManifest.xml 파일 설정 <uses-permission android:name="android.permission.INTERNET"/>


MainActivity.java

package com.example.androidapp; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.app.*; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.*; import android.util.*; import android.widget.*; public class MainActivity extends Activity { String auth_code = "개발자 인증 코드"; 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{ String service = URLEncoder.encode("서울안심먹거리 목록", "UTF-8"); String strUrl = "http://openapi.seoul.go.kr:8088/xml/"+auth_code+"/"+service+"/1/50/"; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(strUrl); HttpResponse response = httpClient.execute(httpGet); InputStream is = response.getEntity().getContent(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line = null; while((line=br.readLine())!=null) { strBuilder.append(line+"\n"); } handler.post(new Runnable() { public void run() { tv.setText(strBuilder.toString()); } }); }catch(Exception ex) { ex.printStackTrace(); Log.e("접속오류", ex.toString()); } } }