標籤:url 源碼 http
上一篇文章主要介紹的圖片檔案的下載與顯示,這一篇文章主要介紹如何根據網頁的地址,擷取網頁原始碼的擷取
其實,網站原始碼的擷取比圖片的下載與顯示更加簡單,只需要對之前的代碼稍作修改即可
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;}};};@Overrideprotected 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);// 設定擷取圖片的方式為GETconn.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" />