利用AsyncTask進行網絡操作之下載HTML

</pre>一方面鞏固下AsyncTasK 的用法,另一方面熟悉下基本的網絡操作。<p></p><p>那麼我們一邊實踐一邊學習吧:</p><p>網絡操作必須記得在manifest.xml 加入:</p><p></p><pre name="code" class="html"><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

1.聯網的方式:

Android 中提供了 HTTPClient 和 HttpURLConnection 兩種方式 二者均支持HTTPS ,流媒體上傳和下載,可配置的超時, IPv6 與連接池(connection pooling)。官方推薦使用HttpURLConnection(Android2.3以上版本,一般我都是用的API14以上,Android4.0)。

2.官方文檔中建議是先檢查網絡連接,當前網絡是否可用

	// 檢測當前網絡是否可用
	private Boolean testInternet() {
		// TODO Auto-generated method stub
		// framework層的管理器
		ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWorkInfo = conMgr.getActiveNetworkInfo();
		if (netWorkInfo != null && netWorkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

3.創建AsyncTask 這裏我暫不貼出代碼,最下面貼出完整代碼。

4.創建downloadUrl() 執行下載html

我們使用 HttpURLConnection 來執行一個 GET 類型的操作並下載數據。在調用 connect()之後,通過調用getInputStream()來得到一個包含數據的InputStream 對象。

// 下載html頁面
	private String downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		// 這裏只打印char[500]的字符
		int len = 500;
		try {
			URL url = new URL(myurl);
			//創建HttpURLConnection對象,打開端口
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//設置讀取,連接超時時間,單位是毫秒
			conn.setReadTimeout(10000);
			conn.setConnectTimeout(15000);
			//請求方式爲GET
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			//建立連接
			conn.connect();	
			int response = conn.getResponseCode();
			Log.d(DEBUG_TAG, "The response is: " + response);
			//獲取InputSream
			is = conn.getInputStream();
			//把InputStream 轉爲 String
			String contentAsString = readIt(is, len);
			return contentAsString;
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

注意:getResponseCode() 會返回連接狀態碼( status code). 這是一種獲知額外網絡連接信息的有效方式。status code 是 200 則意味着連接成功.

5.編寫上面的readIt(),把InputStream 轉爲String,方便顯示。

下面貼出完整代碼:

佈局文件:

<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"
    tools:context="${relativePackage}.${activityClass}" >
    
    <EditText 
        android:id="@+id/et_url"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:hint="enter url"
        />

    <Button 
        android:id="@+id/btn"
        android:layout_below="@id/et_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="download"
        />
    <TextView
        android:layout_below="@id/btn"
        android:layout_margin="20dp"
        android:id="@+id/tv_html"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:gravity="center"/>

</RelativeLayout>

MainActivity:

package com.zero.httpdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String DEBUG_TAG = "debug";
	private TextView tv;
	private Button btn;
	private EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		tv = (TextView) findViewById(R.id.tv_html);
		btn = (Button) findViewById(R.id.btn);
		et = (EditText) findViewById(R.id.et_url);

		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (testInternet()) {
					String urls[] = {"http://"+et.getText().toString()};
					new DownloadWebPage().execute(urls);
				} else {
					Toast.makeText(getApplicationContext(),
							"Can't connect Internet!", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});

	}

	private class DownloadWebPage extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... urls) {
			try {
				return downloadUrl(urls[0]);
			} catch (IOException e) {
				return "URL may be invalid.";
			}
		}
		@Override
		protected void onPostExecute(String result) {
			tv.setText(result);
		}
	}

	// 檢測當前網絡是否可用
	private Boolean testInternet() {
		// TODO Auto-generated method stub
		// framework層的管理器
		ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWorkInfo = conMgr.getActiveNetworkInfo();
		if (netWorkInfo != null && netWorkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	// 下載html頁面
	private String downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		// 這裏只打印char[500]的字符
		int len = 500;
		try {
			URL url = new URL(myurl);
			//創建HttpURLConnection對象,打開端口
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//設置讀取,連接超時時間,單位是毫秒
			conn.setReadTimeout(10000);
			conn.setConnectTimeout(15000);
			//請求方式爲GET
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			//建立連接
			conn.connect();	
			int response = conn.getResponseCode();
			Log.d(DEBUG_TAG, "The response is: " + response);
			//獲取InputSream
			is = conn.getInputStream();
			//把InputStream 轉爲 String
			String contentAsString = readIt(is, len);
			return contentAsString;
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	// 把InputStream 轉換爲字符串,顯示在TextView中
	public String readIt(InputStream stream, int len) throws IOException,
			UnsupportedEncodingException {
		Reader reader = null;
		reader = new InputStreamReader(stream, "UTF-8");
		char[] buffer = new char[len];
		reader.read(buffer);
		return new String(buffer);
	}
}
如果對AsyncTask還不熟悉,可以看我上一篇blog哦!

效果圖:



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