android 網路_網路源碼查看器,android源碼

來源:互聯網
上載者:User

android 網路_網路源碼查看器,android源碼

xml設計

<?xml version="1.0"?>-<LinearLayout tools:context=".MainActivity" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android"><EditText android:id="@+id/et_url" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="http://www.baidu.com"/><Button android:id="@+id/bt_looksource" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="查看源碼"/>-<ScrollView android:layout_height="wrap_content" android:layout_width="wrap_content"><TextView android:id="@+id/tv_source" android:layout_height="match_parent" android:layout_width="match_parent"/></ScrollView></LinearLayout>幾個控制項

 

 

java

package com.itheima.sourcelook;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.app.Activity;import android.content.Context;import android.text.TextUtils;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener{ private EditText et_url; private TextView tv_source; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext =this; et_url = (EditText) findViewById(R.id.et_url); Button bt_looksource = (Button) findViewById(R.id.bt_looksource); tv_source = (TextView) findViewById(R.id.tv_source); //二.設定點擊事件 bt_looksource.setOnClickListener(this); System.out.println("oncreate方法線程:"+Thread.currentThread().getName()); } //☆☆☆1.在主線程中建立一個Handler對象 private Handler handler = new Handler(){ //☆☆☆2.重寫handler的handlermessage方法,用來接收子線程中發來的訊息 public void handleMessage(android.os.Message msg) { //☆☆☆5.接收子線程發送的資料,處理資料。 String result = (String) msg.obj; //☆☆☆6.當前方法屬於主線程可以做UI的更新 //五.擷取伺服器返回的內容,顯示到textview上 tv_source.setText(result); }; }; @Override public void onClick(View v) { try{ //三.oclick方法中擷取使用者輸入的url地址 final String url_str = et_url.getText().toString().trim(); if(TextUtils.isEmpty(url_str)){ Toast.makeText(mContext, "url不可為空", 0).show(); return ; } System.out.println("oclick方法線程:"+Thread.currentThread().getName()); //建立一個子線程做網路請求 new Thread(new Runnable() { @Override public void run() { try{ System.out.println("oclick方法runnable線程:"+Thread.currentThread().getName()); //四.請求url地址 //1.建立一個Url對象 URL url = new URL(url_str); //2.擷取一個UrlConnection對象 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); //3.為UrlConnection對象設定一些請求的參數,請求方式,串連的逾時時間 connection.setRequestMethod("GET");//佈建要求方式 connection.setConnectTimeout(1000*10);//設定逾時時間 //4.在擷取url請求的資料前需要判斷響應碼,200 :成功,206:訪問部分資料成功 300:跳轉或重新導向 400:錯誤 500:伺服器異常 int code = connection.getResponseCode(); if(code == 200){ //5.擷取有效資料,並將擷取的流資料解析成String InputStream inputStream = connection.getInputStream(); String result = StreamUtils.streamToString(inputStream); //☆☆☆3.子線中建立一個Message對象,為了攜帶子線程中擷取的資料給主線程。 Message msg = new Message(); msg.obj = result;//將擷取的資料封裝到msg中。 //☆☆☆4.使用handler對象將message發送到主線程。 handler.sendMessage(msg); } }catch (Exception e) { e.printStackTrace(); } } }).start(); }catch (Exception e) { e.printStackTrace(); } }}MainActivity

 

package com.itheima.sourcelook;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamUtils { public static String streamToString(InputStream in){ String result =""; try{ //建立一個位元組數組寫入流 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ( (length = in.read(buffer)) !=-1) { out.write(buffer, 0, length); out.flush(); } result = out.toString();//將位元組流轉換成string out.close(); }catch (Exception e) { e.printStackTrace(); } return result; }}StreamUtils--包--位元組--字串

 

老師筆記

# 01 網路html源碼查看器
    
    訪問網路需要加Internet許可權:
    android.permission.INTERNET

        
    使用UrlConnection請求一個url地址擷取內容:

            //1.建立一個Url對象
                URL url = new URL(url_str);
            //2.擷取一個UrlConnection對象
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //3.為UrlConnection對象設定一些請求的參數,請求方式,串連的逾時時間
                connection.setRequestMethod("GET");//佈建要求方式
                connection.setConnectTimeout(1000*10);//設定逾時時間
            //4.在擷取url請求的資料前需要判斷響應碼,200 :成功,206:訪問部分資料成功   300:跳轉或重新導向  400:錯誤 500:伺服器異常
                int code = connection.getResponseCode();
                if(code == 200){
            //5.擷取有效資料,並將擷取的流資料解析成String
                    InputStream inputStream = connection.getInputStream();
                    String result = StreamUtils.streamToString(inputStream);
    


    注意事項:
        
        1. ANR:application not response 應用無響應; androoid中耗時的操作(請求網路,大檔案的拷貝,資料庫的操作)需要在子線程中做。
        09-02 01:52:40.711: E/ActivityManager(857): ANR in com.itheima.sourcelook (com.itheima.sourcelook/.MainActivity)

        2. 4.0後網路操作強制在子線程中進行。因為網路訪問是耗時的操作,可能會導致ANR
        09-02 01:57:32.879: W/System.err(1789):  android.os.NetworkOnMainThreadException

        3.錯誤線程調用異常,子線程不能夠更新UI(控制項的內容)
            09-02 02:02:08.873: W/System.err(1858): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

    
        主線程不能夠做耗時的操作,網路請求就是耗時的操作需要放到子線程做。子線程不能更新控制項的內容(更新Ui)。所以產生了矛盾,解決辦法就是使用Handler.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.