Androud中的Http通信之WebView

AndroidMenifest.xml添加權限

<uses-permission android:name="android.permission.INTERNET"/>

佈局添加WebView

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.lune.http_01.MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</LinearLayout>


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;

import com.lune.thread.HttpThread;



public class MainActivity extends Activity {

    private WebView webView;
    private Handler handler = new Handler();

    //通過http訪問百度網址信息
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webView = (WebView)findViewById(R.id.webView);
        new HttpThread("http://www.baidu.com",webView,handler).start();
    }
}

其中的HttpThread爲自己定義的一個線程

import android.os.Handler;
import android.webkit.WebView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpThread extends Thread{
    //網絡的訪問是一個耗時的操作,因此在線程中進行

    private String url;
    private WebView webView;
    Handler handler;    //子線程中更新url

    public HttpThread(String url,WebView webView,Handler handler){
        this.url = url;
        this.webView = webView;
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            URL httpUrl = new URL(url);       //統一資源定位符對象
            try {
                HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                //通過conn設置連接參數
                conn.setReadTimeout(5000);  //設置讀取超時時間
                conn.setRequestMethod("GET"); //設置請求方式

                final StringBuffer sb = new StringBuffer();
                String str;
                //網頁回傳的頁面信息通過reader讀取
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while((str=reader.readLine())!=null){
                    sb.append(str);
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadData(sb.toString(),"text/html;charset=utf-8",null);
                    }
                });
                           } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }
}



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