본문 바로가기

Android/HttpClient, GET, text

Android HttpClient, GET example

안드로이드에서 HttpClient를 이용하여 웹사이트의 HTML 코드를 가져와서 출력하는 예

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>


AndroidManifest.xml 에는 다음과 같이 권한을 설정하는 부분이 있어야 한다

<uses-permission android:name="android.permission.INTERNET"/>


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 android.app.*; import android.os.*; import android.util.*; import android.widget.*; public class MainActivity extends Activity { TextView tv; Handler handler = new Handler(); StringBuilder strBuilder = new StringBuilder();

@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(); } private void connect() { try{ HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://naver.com"); HttpResponse response = httpClient.execute(httpGet); InputStream is = response.getEntity().getContent(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while((line=br.readLine())!=null) { strBuilder.append(line+"\n"); } br.close();

/* 유저 쓰레드에서는 UI를 갱신할 수 없으므로 메인 쓰레드에게 화면갱신을 의뢰한다

* handler.sendMessage()를 사용하여 메인 쓰레드 내에서 handleMessage()가 실행되도록 할 수도 있지만 * Runnable객체를 생성하여 메인 쓰레드에게 전달 및 실행을 의뢰하면 코드가 좀더 간결해진다 */

handler.post(new Runnable() { public void run() { tv.setText(strBuilder.toString()); } }); }catch(Exception ex) { ex.printStackTrace(); Log.e("접속오류", ex.toString()); } } }