首页 > 代码库 > 【Android进阶】使用HttpURLConnection实现网页源码的下载

【Android进阶】使用HttpURLConnection实现网页源码的下载

上一篇文章主要介绍的图片文件的下载与显示,这一篇文章主要介绍如何根据网页的地址,获取网页源代码的获取

其实,网站源代码的获取比图片的下载与显示更加简单,只需要对之前的代码稍作修改即可


public class OtherActivity extends Activity {

	private TextView tv;
	private static final int LOAD_SUCCESS = 1;
	private static final int LOAD_ERROR = -1;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case LOAD_SUCCESS:
				tv.setText((String) msg.obj);
				break;
			case LOAD_ERROR:
				Toast.makeText(getApplicationContext(), "加载失败", 0).show();
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);
	}

	// Button的点击事件
	public void show(View view) {
		new Thread(new Runnable() {
			public void run() {
				getHttp();
			}
		}).start();

	}

	// 下载图片的主方法
	private void getHttp() {
		URL url = null;
		InputStream is = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			// 构建图片的url地址
			url = new URL("http://www.baidu.com");
			// 开启连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置超时的时间,5000毫秒即5秒
			conn.setConnectTimeout(5000);
			// 设置获取图片的方式为GET
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				is = conn.getInputStream();
				byteArrayOutputStream = new ByteArrayOutputStream();
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					byteArrayOutputStream.write(buffer, 0, len);
				}
				byteArrayOutputStream.flush();
				byte[] arr = byteArrayOutputStream.toByteArray();
				Message msg = handler.obtainMessage();
				msg.what = LOAD_SUCCESS;
				msg.obj = new String(arr);
				handler.sendMessage(msg);
			}
		} catch (Exception e) {
			handler.sendEmptyMessage(LOAD_ERROR);
			e.printStackTrace();
		} finally {

			try {
				if (is != null) {
					is.close();
				}
				if (byteArrayOutputStream != null) {
					byteArrayOutputStream.close();
				}
			} catch (Exception e) {
				handler.sendEmptyMessage(LOAD_ERROR);
				e.printStackTrace();
			}
		}
	}

}

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:onClick="show"
        android:text="显示" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

权限

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