【Android】Android取网页源码,解决各种坑,高级编程思想,附效果图。环境:Android studio-子木科技
大家好,5.1了,给大家写一篇博文,关于android平台的一些操作,还有一些坑的解决,今天主要给大家写一篇取网页源码的android博文。
作者qq:936237071
环境:android studio,小米8.
本来我是想写一个菜谱app,然后中间我要取网页的源代码。
效果图:
我取的网页编码是gb2312格式,取其他的格式更换方法编码就行。
取源代码首先给xml里面加网络访问权限。
<uses-permission android:name="android.permission.INTERNET"/>
其次我是建立了个操作类,直接新建的。附图
为了简单明了,我使用中文写的名字,因为我懒得写备注
调用方法:
注意点:
1.因为接口写了throws Exception 所以必须用try catch捕获
2.因为安卓4.4之后不允许在主线程直接访问网络,所以必须开一个线程,否则抛出异常
主界面布局(我们只用了其中两个控件)
接下来给按钮点击绑定事件aass
操作类的代码:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class cz {
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public static String 取网页源码(String 地址,String 网页编码) throws Exception {
// 通过网络地址创建URL对象
URL url = new URL(地址);
// 根据URL
// 打开连接,URL.openConnection函数会根据URL的类型,返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设定URL的请求类别,有POST、GET 两类
conn.setRequestMethod("GET");
//设置从主机读取数据超时(单位:毫秒)
conn.setConnectTimeout(5000);
//设置连接主机超时(单位:毫秒)
conn.setReadTimeout(5000);
// 通过打开的连接读取的输入流,获取html数据
InputStream inStream = conn.getInputStream();
// 得到html的二进制数据
byte[] data = readInputStream(inStream);
// 是用指定的字符集解码指定的字节数组构造一个新的字符串
String html = new String(data, 网页编码);
return html;
}
}
方法的代码:
public void aass(View s){
new Thread(new Runnable(){
@Override
public void run() {
// AlertDialog.Builder ab=new AlertDialog.Builder(getApplicationContext()); //(普通消息框)
try{
TextView aa =(TextView)findViewById(R.id.html);
String sb=cz.取网页源码("http://tools.2345.com/frame/menu/search?keyword=%B3%B4%C8%E2","gb2312");
aa.setText(sb);
}
catch (Exception e){
TextView aa =(TextView)findViewById(R.id.search);
aa.setText(e.toString());
}
}
}).start();
}