现在的位置: 首页 > 综合 > 正文

java 获取网页源代码

2013年07月27日 ⁄ 综合 ⁄ 共 2284字 ⁄ 字号 评论关闭

要分析某个网页中的代码构成,需要某个结点下的内容。用此原始方法可以得到整个网页的源码。其实更简单的方法是使用 WebClient 或 HtmlUtil 等开源方式 。

[java] view
plain
copy

  1. public class HtmlParser {  
  2.     public static String getHtmlContent(URL url, String encode) {  
  3.         StringBuffer contentBuffer = new StringBuffer();  
  4.   
  5.         int responseCode = -1;  
  6.         HttpURLConnection con = null;  
  7.         try {  
  8.             con = (HttpURLConnection) url.openConnection();  
  9.             con.setRequestProperty("User-Agent""Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");// IE代理进行下载  
  10.             con.setConnectTimeout(60000);  
  11.             con.setReadTimeout(60000);  
  12.             // 获得网页返回信息码  
  13.             responseCode = con.getResponseCode();  
  14.             if (responseCode == -1) {  
  15.                 System.out.println(url.toString() + " : connection is failure...");  
  16.                 con.disconnect();  
  17.                 return null;  
  18.             }  
  19.             if (responseCode >= 400// 请求失败  
  20.             {  
  21.                 System.out.println("请求失败:get response code: " + responseCode);  
  22.                 con.disconnect();  
  23.                 return null;  
  24.             }  
  25.   
  26.             InputStream inStr = con.getInputStream();  
  27.             InputStreamReader istreamReader = new InputStreamReader(inStr, encode);  
  28.             BufferedReader buffStr = new BufferedReader(istreamReader);  
  29.   
  30.             String str = null;  
  31.             while ((str = buffStr.readLine()) != null)  
  32.                 contentBuffer.append(str);  
  33.             inStr.close();  
  34.         } catch (IOException e) {  
  35.             e.printStackTrace();  
  36.             contentBuffer = null;  
  37.             System.out.println("error: " + url.toString());  
  38.         } finally {  
  39.             con.disconnect();  
  40.         }  
  41.         return contentBuffer.toString();  
  42.     }  
  43.   
  44.     public static String getHtmlContent(String url, String encode) {  
  45.         if (!url.toLowerCase().startsWith("http://")) {  
  46.             url = "http://" + url;  
  47.         }  
  48.         try {  
  49.             URL rUrl = new URL(url);  
  50.             return getHtmlContent(rUrl, encode);  
  51.         } catch (Exception e) {  
  52.             e.printStackTrace();  
  53.             return null;  
  54.         }  
  55.     }  
  56.     public static void main(String argsp[]){  
  57.         System.out.println(getHtmlContent("www.baidu.com","utf-8")) ;  
  58.           
  59.     }  
  60. }  

抱歉!评论已关闭.