html代码查看器
1.新建一个Android工程
2.构建布局文件.添加网络访问权限
3.在主Activity中实现点击事件
public void viewHtml(View view) {
String path = et_path.getText().toString();
try {
String content = HtmlService.getHtmlContent(path);
if (content != null) {
tv_content.setText(content);
}else {
tv_content.setText("获取数据失败");
}
} catch (Exception e) {
e.printStackTrace();
tv_content.setText("获取数据失败");
}
}
4.创建Service包中的HtmlService类
public static String getHtmlContent(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 is = conn.getInputStream();
byte[] data = StreamTool.getStreamBytes(is);
return new String(data);
}
return null;
}
如果出现乱码,可以先查看出网页使用是哪种编码格式.然后在return new String(data,"编码格式")中指定.
5.创建工具包中的StreamTool类
//把inputstream的信息 转化成byte[] 返回
public static byte[] getStreamBytes(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = is.read(buffer))!=-1 ){
baos.write(buffer, 0, len);
}
byte[] result = baos.toByteArray();
is.close();
baos.close();
return result;
}
6.获取到的内容过多在TextView中显示不去的话.可以定义个ScrollView控件,把TextView放进去即可.
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
程序员编程交流QQ群:805358732
如果你想用Python开辟副业赚钱,但不熟悉爬虫与反爬虫技术,没有接单途径,也缺乏兼职经验
关注下方微信公众号:Python编程学习圈,获取价值999元全套Python入门到进阶的学习资料以及教程,还有Python技术交流群一起交流学习哦。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!