若想使自己的android運用連網,必須要在AndroidManifest.xml中擷取連網的許可權,(即在裡面添加 <uses-permission android:name="android.permission.INTERNET" />代碼)
如下圖所示:
然後就是寫頁面的代碼了,(即:本文中的activity_main.xml檔案)
<ScrollView 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=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <EditText android:id="@+id/edturl" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="輸入網站" android:inputType="textUri" android:singleLine="true" /> <Button android:id="@+id/requesthtml" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="擷取html代碼" /> <EditText android:id="@+id/edthttp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="這裡顯示的是你所輸入的網站的HTML代碼" /> </LinearLayout></ScrollView>
重點來了,那是java檔案的代碼,不過,在這說一下注意的東西:在android 2.3版本以上,不能直接在主線程上連網,否則會拋出 android.os.NetworkOnMainThreadException的錯誤,這是因為在連網的過程中,程式會發送請求以便擷取資料,但假如直接在主線程發送請求的話,頁面就會卡住,進入假死狀態。android後來版本為了預防這種情況,於是。。。。
因此,我們連網需要非同步來操作。因為我之前都是用Thread的,現在想換換其它東西,就用了AsyncTask。
於是Java檔案分為兩部分,第一部分是控制頁面效果和監聽的,第二部分是用來執行非同步作業。
第一部分代碼如下:
import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {// 定義組件private EditText edtURL;private EditText edtHTTP;private Button btnRequest;private String strURL;// 用於儲存網站地址private MyTask myTask;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 初始化組件edtURL = (EditText) findViewById(R.id.edturl);edtHTTP = (EditText) findViewById(R.id.edthttp);btnRequest = (Button) findViewById(R.id.requesthtml);// 監聽擷取html代碼的按鈕btnRequest.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (!(strURL = edtURL.getText().toString()).equals("")) {//執行個體myTask對象myTask = new MyTask(edtHTTP);myTask.execute(strURL);}}});}}
第二部分代碼:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import com.xiaoyan.httpclienttest.R.integer;import android.os.AsyncTask;import android.widget.EditText;/** * 用於非同步作業來讀取網頁中HTML代碼 * * @author jianyan * */public class MyTask extends AsyncTask<String, integer, StringBuffer> {private EditText edtHTTP;// 用於顯示HTML代碼private StringBuffer sbHTML;// 用於儲存HTML代碼public MyTask(EditText edtHTTP) {this.edtHTTP = edtHTTP;sbHTML = new StringBuffer();}/** * doInBackground方法內部執行背景工作,不可在此方法內修改UI */@Overrideprotected StringBuffer doInBackground(String... params) {// 初始化HTTP的用戶端HttpClient hc = new DefaultHttpClient();// 執行個體化HttpGet對象HttpGet hg = new HttpGet(params[0]);try {// 讓HTTP用戶端已Get的方式請求資料,並把所得的資料賦值給HttpResponse的對象HttpResponse hr = hc.execute(hg);// 使用緩衝的方式讀取所返回的資料BufferedReader br = new BufferedReader(new InputStreamReader(hr.getEntity().getContent()));// 讀取網頁所返回的HTML代碼String line = "";sbHTML = new StringBuffer();while ((line = br.readLine()) != null) {sbHTML.append(line);}return sbHTML;} catch (IOException e) {edtHTTP.setText("擷取網頁HTML代碼出錯。。。");}return null;}/** * onPostExecute方法用於在執行完背景工作後更新UI,顯示結果 */@Overrideprotected void onPostExecute(StringBuffer result) {// 判斷是否為null,若不為null,則在頁面顯示HTML代碼if (result != null) {edtHTTP.setText(result);}super.onPostExecute(result);}}
所有代碼都在上面了,然後我們看看啟動並執行效果:(測試機:中興U808)
源碼地址如下: [android] 擷取網頁中的HTML資料