Android中的Http通信(二)之根據Url讀取網絡數據

廢話不多說,直接開始吧。如果你看到了這一篇文章,但是你對Http協議的基本知識還不夠了解,那你就去看上一篇文章:Android中的Http通信(一)之Http協議基本知識。本篇文章主要介紹的是,根據url讀取網頁html,並且顯示到webview上面。文章很簡單,內容也很簡單,那我爲什麼還要寫呢,目的就是就是爲了瞭解和熟悉URL對象和HttpURLConnection對象的使用。

廢話不多說,直接看佈局吧:

<RelativeLayout 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" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
很簡單,不做任何介紹。

看看Activity中的代碼:

package com.example.http;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;

/**
 * 根據一個URL,通過Http協議,讀取其中的HTML代碼,並顯示到webView上
 * 
 * @author xiaoyf
 * 
 */
public class MainActivity extends Activity {
	private WebView mWebView;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mWebView = (WebView) findViewById(R.id.webView);
		String url = "http://blog.csdn.net/u014544193/article/details/49849843";
		new HttpThread(url, mWebView, handler).start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

也是很easy的,看不懂的話,你還是學學基礎吧委屈

下面是URL和HttpURLConnection應用的核心代碼,也是本篇的核心。

package com.example.http;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Handler;
import android.webkit.WebView;

/**
 * 爲讀取網絡數據所開闢的子線程
 * 
 * @author xiaoyf
 * 
 */
public class HttpThread extends Thread {
	private final static int CONNECT_OUT_TIME = 5000;
	private String url;
	private WebView webView;
	private Handler handler;

	public HttpThread() {
		super();
	}

	public HttpThread(String url, WebView webView, Handler handler) {
		super();
		this.url = url;
		this.webView = webView;
		this.handler = handler;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			// 第一步:創建必要的URL對象
			URL httpUrl = new URL(url);
			// 第二步:根據URL對象,獲取HttpURLConnection對象
			HttpURLConnection connection = (HttpURLConnection) httpUrl
					.openConnection();
			// 第三步:爲HttpURLConnection對象設置必要的參數(是否允許輸入數據、連接超時時間、請求方式)
			connection.setDoInput(true);
			connection.setConnectTimeout(CONNECT_OUT_TIME);
			connection.setRequestMethod("GET");
			// 第四步:開始讀取數據
			final StringBuffer buffer = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				buffer.append(temp);
			}
			reader.close();

			handler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					webView.loadData(buffer.toString(),
							"text/html;charset=utf-8", "utf-8");
				}
			});

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

流程就是:創建URL對象----->根據URL對象獲取HttpURLConnection對象----->爲HttpURLConnection對象設置必要的參數----->開始讀取數據----->通過handler對象,將html代碼顯示到webview上


項目下載:http://download.csdn.net/detail/u014544193/9337639


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章