作者在 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"/>