一、需要在清单文件中注册网络权限
二、建立一个工具类 HtmlService.java
1.第一个方法用 get方法获取网页的源码,在return返回
public static String getHtml(String path)throws Exception{
URL url =new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
InputStream itstream = conn.getInputStream();
byte[] data =readInputStream(itstream);
String html =new String(data,"UTF-8");
return html;
}
2.第二个方法,解析返回的数据
private static byte[] readInputStream(InputStream inStream)throws Exception {
ByteArrayOutputStream outStream =new ByteArrayOutputStream();
byte[] butffte =new byte[1024];
int len=0;
while ((len=inStream.read(butffte))!=-1){
outStream.write(butffte,0,len);
}
inStream.close();
return outStream.toByteArray();
}
3.在MainActivity中调用HtmlService这个类
1.在活动中调用网络操作需要用子线程来操作.
new Thread(){
@Override
public void run() {
try{
String doc = HtmlService.getHtml(“这里是获取网页的网址”);
date = doc.toString();
Log.d(String.valueOf(this),"数据:"+date);
}catch (Exception e){
Log.d(String.valueOf(this),"程序异常"+e.toString());
}
}
}.start();
直接将这个子线程写进方法里面就完成.
出处:唐瀚林
——挥舞着本子和键盘,要将这世界写个明白.
网友评论