java程序读取一个url页面的源代码

java程序读取一个url页面的源代码,比如 www.baidu.com

传入一个url,返回源代码; public static String getHTML(String url){// 获取指定URL的网页,返回网页内容的字符串,然后将此字符串存到文件即可 try { URL newUrl = new URL(url); URLConnection connect = newUrl.openConnection(); connect.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); DataInputStream dis = new DataInputStream(connect.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(dis,"UTF-8")); String html = ""; String readLine = null; while((readLine = in.readLine()) != null) { html = html + readLine; } in.close(); return html; }catch (MalformedURLException me){ System.out.println("MalformedURLException" + me); }catch (IOException ioe){ System.out.println("ioeException" + ioe); } return null; }
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答
大家正在搜