HttpURLConnection,通过WebView显示指定网页
<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">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
public class MainActivity extends ActionBarActivity {
private WebView webView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
new HttpThread(handler,webView,"https://www.baidu.com").start();
}
}
public class HttpThread extends Thread{
private String url;
private Handler handler;
private WebView webView;
public HttpThread(Handler handler,WebView webView,String url){
this.handler = handler;
this.webView = webView;
this.url = url;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer sb = new StringBuffer();
String str;
while((str = br.readLine()) != null)
{
sb.append(str);
}
//更新UI
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
webView.loadData(sb.toString(), "text/html;charset=utf-8", null);
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:
![这里写图片描述](http://img.blog.csdn.net/20160223130144453)