Android studio 解析网页数据,把网页Json格式的数据提取到Android studio上

工具类

HtmlService

具体实现如下:

public class HtmlService {

    public static String getHtml(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();//通过输入流获取html数据
        byte[] data = readInputStream(inStream);//得到html的二进制数据
        String html = new String(data, "UTF-8");
        return html;
    }
    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();
    }
}
 

当想要获取网页数据时,比如天气 http://wthrcdn.etouch.cn/weather_mini?city长沙

其网页显示结果如下:

然后

String path= http://wthrcdn.etouch.cn/weather_mini?city长沙;

String html=html = HtmlService.getHtml(path);

html就是结果

你可能感兴趣的:(Android studio 解析网页数据,把网页Json格式的数据提取到Android studio上)