如何用java语言获取某个网页的源代码

时间:2024-03-08 11:08:28
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;


public class WebPageResource {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		WebPageResource t6 = new WebPageResource();
		String htmls = t6.getPageResource("http://www.keyanhome.com/", "UTF-8");
		System.out.println(htmls);
	}
	
	
	public String getPageResource(String pageURL,String encoding){
		
		StringBuffer sbBuffer = new StringBuffer();
		try {
			URL url = new URL(pageURL);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),encoding));
			String lineString;
			while((lineString=in.readLine())!=null)
			{
				sbBuffer.append(lineString);
				sbBuffer.append("\n");
			}
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return sbBuffer.toString();
		
	}
	
	
	
	

}