1. 程式人生 > >(黎活明老師講學)Android學習(二)---從網路上獲取網頁

(黎活明老師講學)Android學習(二)---從網路上獲取網頁

手機上網瀏覽網頁,獲取到網頁的資訊。

工具類

public class StreamTool {
	
	/**
	 * 從輸入流中獲取資料
	 * @param inStream 輸入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}

耗時操作,繼承AsyncTask類,實現載入網頁

public class HtmlService extends AsyncTask<Void,  Void, String> {
	private String path;
	private TextView textView;
	
	public HtmlService(String path,TextView textView) {
		super();
		this.path = path;
		this.textView = textView;
	}

	/**
	 * 聯網獲取到網址的連結內容
	 * @param path
	 * @return
	 */
	public static String getHtml(String path){	
		try {
			URL url = new URL(path);
			HttpURLConnection conn;
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片資料
			byte[] data = StreamTool.readInputStream(inStream);// 得到圖片的二進位制資料
			String html = new String(data, "UTF-8");
			return html;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected String doInBackground(Void... params) {
		String data = HtmlService.getHtml(path);
		return data;
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}
	
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		textView.setText(result);
	}
	
	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}
}

主執行緒

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 TextView textView = (TextView)this.findViewById(R.id.textView);
		 
		 HtmlService htmlService = new HtmlService("http://www.baidu.com", textView);
		 htmlService.execute();
	}

}