先交代背景
主机:Ubuntu16.04LTS
安装服务:Apache2 http服务,80端口已开启
网络:无线网卡登录 动态分配内网IP 192.168.1.106
1.本地网页已经写入,放在/var/www/html中,设为默认网页.文件名:index.html.因为不进行具体的解析工作,网页代码不加展示.
2.App源代码以及注释
1)网络请求属于耗时操作,将其封装入Thread类中.
public class HttpThread extends Thread{
private String url;
private WebView web;
private Handler handler;
private StringBuffer sb = new StringBuffer();
// 初始化
public HttpThread(String url,WebView web,Handler handler){
this.url = url;
this.web = web;
this.handler = handler;
}
//编写主要耗时操作
@override
public void run(){
try{
URL myUrl = new URL(url);
HttpURLConnection localCon =(HttpURLConnection)myUrl.openConnection();
localCon.setRequestMethod("GET");
//通过Connection对象的open方法拿到输入流,传入InputStreamReader对象中,构建BufferedReader对象
BufferedReader reader = new BufferedReader( new InputStreamReader( localCon.getInputStream() ) );
String str = null;
while( (str=reader.readLine() ) != null){
sb.append(str);
}//while
//发送耗时逻辑
handler.post(new Runnable){
@override
public void run(){
web.loadData(sb.toString(),"text/html;charset=utf-8",null);
}
}//handler
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
}//run
}//class
2)主活动调用即可
Public Class MainActivity extends Activity{
private WebView web;
private Handler handler;
private String str = "http://192.168.1.106";
@override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
initiate();
// **线程必须开启才会生效**,调用start()方法.
new HttpThread(str,web,handler).start();
}
public void initiate(){
web = (WebView)findViewById(R.id.webview);
}
}