28 5월

쓰레드를 사용해서 웹페이지 소스 가져오기

package yell.exam01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import yell.exam01.R;

public class test_network extends Activity {

	downloadThread mThread;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_network);
	}

	public void mOnClick(View v) {

		EditText et = (EditText) findViewById(R.id.textURL);
		ImageView iv = (ImageView) findViewById(R.id.imageview1);

		if (et.getText().toString() != null) {
			mThread = new downloadThread(et.getText().toString());
			mThread.start();
		}
	}

	class downloadThread extends Thread {
		String mAddr;

		public downloadThread(String addr) {
			// TODO Auto-generated constructor stub
			mAddr = addr;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			HttpGet httpget = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
				client.execute(httpget, mResHandler);
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}

		ResponseHandler<string> mResHandler = new ResponseHandler<string>() {
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				// TODO Auto-generated method stub

				Log.d("YELL", "읽기 스트림 시작");

				StringBuilder html = new StringBuilder();
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
					String line = null;
					while ((line = br.readLine()) != null) {
						html.append(line + "\n");
					}
					br.close();

					Log.d("YELL", "끗~ 메시지 보냄");
					Log.d("YELL", html.substring(0, 1000).toString());

					Message message = mAfterDown.obtainMessage();
					Bundle bundle = new Bundle();
					bundle.putString("result", html.toString());
					message.setData(bundle);
					mAfterDown.sendMessage(message);
				}
				catch (Exception e) {
					// TODO: handle exception
				}

				return html.toString();
			}
		};

		Handler mAfterDown = new Handler() {
			public void handleMessage(android.os.Message msg) {
				String sResult = msg.getData().getString("result");
				TextView tv = (TextView) findViewById(R.id.textview_result);
				tv.setText(sResult);
			};
		};
	}
}

답글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다.