JAVA抓取一个HTML源代码

  1.   
  2. package com.hyq.src;   
  3.   
  4. import java.io.InputStream;   
  5. import java.net.URL;   
  6.   
  7.   
  8. public class Test {   
  9.        
  10.     /**  
  11.      * @param args  
  12.      */  
  13.     public static void main(String[] args) {   
  14.         try{   
  15.             Test.testNetStream();   
  16.         }catch(Exception e){   
  17.             e.printStackTrace();   
  18.         }   
  19.     }    
  20.     public static void testNetStream()throws Exception{   
  21.         URL url=new URL("http://www.imust.cn/");   
  22.         InputStream in=url.openStream();   
  23.         byte[] b=new byte[100000];   
  24.         in.read(b);   
  25.         in.close();   
  26.         String s=new String(b);   
  27.         System.out.println(s);   
  28.     }   
  29. }  
package com.hyq.src;

import java.io.InputStream;
import java.net.URL;


public class Test {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try{
			Test.testNetStream();
		}catch(Exception e){
			e.printStackTrace();
		}
	} 
	public static void testNetStream()throws Exception{
		URL url=new URL("http://www.imust.cn/");
		InputStream in=url.openStream();
		byte[] b=new byte[100000];
		in.read(b);
		in.close();
		String s=new String(b);
		System.out.println(s);
	}
}












Java代码 复制代码 收藏代码
  1.   
  2. package com.hyq.src;   
  3.   
  4. import java.io.BufferedReader;   
  5. import java.io.InputStreamReader;   
  6. import java.net.URL;   
  7. import java.net.URLConnection;   
  8.   
  9.   
  10.   
  11. public class Test {   
  12.        
  13.     public static void main(String[] args)   
  14.     {   
  15.         System.out.println(Test.getHtmlSource("http://sports.163.com/zc/"));   
  16.     }   
  17.        
  18.     public static String getHtmlSource(String url){   
  19.         StringBuffer stb=new StringBuffer();   
  20.         try{   
  21.             URLConnection uc=new URL(url).openConnection();   
  22.             BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream(),"gb2312"));   
  23.             String temp=null;   
  24.             while((temp=br.readLine())!=null){   
  25.                 stb.append(temp).append("\n");   
  26.             }   
  27.             br.close();   
  28.                
  29.         }catch(Exception e){   
  30.             e.printStackTrace();   
  31.         }   
  32.         return stb.toString();   
  33.            
  34.     }   
  35.   
  36.        
  37. }  
posted @ 2011-09-22 22:32  星月磊子  阅读(596)  评论(0编辑  收藏  举报