java获取到超链接的内容

参考文档 : https://blog.****.net/jfh389987366/article/details/79375527

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Url {

    public static void main(String[] args) throws Exception {
        String url="http://flash.weather.com.cn/wmaps/xml/chengdu.xml";
        getData(url);
    }

    public static String getData(String urlString) throws Exception {
        String res = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            URLConnection conn = (URLConnection)url.openConnection();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            System.out.println("创建url!");
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("分别获取每行内容!:"+line);
                res += line;
            }
            reader.close();
        } catch (Exception e) {
            e.getMessage();
        }
        System.out.println(res);
        return res;
    }
}
 
返回结果:

java获取到超链接的内容

原网页内容:

java获取到超链接的内容

接下来就可以解析其中自己需要的内容了(上面例子中返回的数据是xml格式的字符串,如果需要返回数据流请参考上面原教程)