Android通过访问网页查看网页源码实例详解
程序员文章站
2023-12-11 21:07:10
android通过访问网页查看网页源码
1.添加网络权限
android通过访问网页查看网页源码
1.添加网络权限
<!--访问网络的权限--> <uses-permission android:name="android.permission.internet"/>
2.获取网络中网页的数据
/** * 获取网页html源代码 * @param path 网页路径 */ public static string gethtml(string path) throws exception { url url=new url(path); httpurlconnection conn=(httpurlconnection)url.openconnection(); conn.setconnecttimeout(5000); conn.setrequestmethod("get"); if(conn.getresponsecode()==200){ inputstream instream=conn.getinputstream(); byte[] data=read(instream); string html=new string(data,"utf-8"); return html; } return null; } /** * 读取流中的数据 */ public static byte[] read(inputstream inputstream) throws ioexception { bytearrayoutputstream outputstream=new bytearrayoutputstream(); byte[] b=new byte[1024]; int len=0; while((len=inputstream.read(b))!=-1){ outputstream.write(b); } inputstream.close(); return outputstream.tobytearray(); }
3.处理查看网页源码的控制
public class htmlviewactivity extends activity { private edittext pathtext; private textview codeview; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); pathtext=(edittext) findviewbyid(r.id.pagepath);//网页路径 codeview=(textview)findviewbyid(r.id.codeview);//显示获得的源码 button button=(button) findviewbyid(r.id.button);//查看按钮 button.setonclicklistener(new buttonclicklistener());//按钮事件 } /** * 查看按钮处理事件 */ private final class buttonclicklistener implements view.onclicklistener{ @override public void onclick(view v) { string path=pathtext.gettext().tostring(); try { string html=pageservice.gethtml(path); codeview.settext(html); } catch (exception e) { e.printstacktrace(); toast.maketext(getapplicationcontext(), r.string.error, 1); } } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!