httpweb 线程处理

作者在 2016-04-07 00:34:50 发布以下内容
public class Httpthread extends Thread{
	String url;
	WebView webView;
	Handler handler;
	public Httpthread(String url, WebView webView,Handler handler){
		this.url=url;
		this.webView=webView;
		this.handler=handler;
	}
	
	public void run(){
		try {
			URL httpUrl=new URL(url);
			try {
				HttpURLConnection conn=(HttpURLConnection) httpUrl.openConnection();
				conn.setReadTimeout(5000);
				conn.setRequestMethod("GET");
				final StringBuffer sb=new StringBuffer();
				BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String str;
				while((str=br.readLine())!=null){
					sb.append(str);
					
					
				}
		
				handler.post(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
					webView.loadData(sb.toString(), "text/html;charset=utf-8", null);	
					}
					
				});
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}



////////////////////////////////////////

public class MainActivity extends Activity {
Handler handler=new Handler();
WebView webView;
Httpthread httpthread;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView=(WebView) findViewById(R.id.webview);
      
        new Httpthread("http://www.bccn.net", webView, handler).start();
        
    }
///////////////////////////////////////////////////////
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_world" />

</RelativeLayout


//////////////////////////
PS:
 
    <uses-permission android:name="android.permission.INTERNET"/>
360截图20160407003425124.jpg (上传于2016-04-07 00:42:21)
360截图20160407003425124.jpg
android | 阅读 12445 次
文章评论,共0条
游客请输入验证码
浏览239627次
最新评论