备注:安卓8.0以上需要在xml中配置
usescleartexttraffic=true
最近在网上找了一些安卓取网页源码的实例,很多都不能用。
所以自己查了一些资料写了一个获取网页源码实例.
主方法:
@Override
public void onClick(View v) {
final String IP_URL="http://www.baidu.com";
//网络属于耗时操作 需要多线程来运行 否则会异常
new Thread(new Runnable(){
public void run(){
//获取服务端的url
try {
really_url=Initial.GetHtml(IP_URL);
System.out.println(really_url);
}catch(Exception e){
System.err.println("错误");
}
}
}).start();
取网页源码方法
String GetHtml(String url1){
String str="";
try
{
URL url = new URL(url1);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
String location = conn.getRequestProperty("location");
int resCode = conn.getResponseCode();
conn.connect();
InputStream stream = conn.getInputStream();
byte[] data=new byte[102400];
int length=stream.read(data);
str=new String(data,0,length);
conn.disconnect();
System.out.println(str);
stream.close();
}
catch(Exception ee)
{
System.out.print("ee:"+ee.getMessage());
}
return str;
}
运行结果:
如有错误,大佬指正。