JAVA用URL下载网页为静态页面

1.可以作为项目的动态页面生成静态页面的功能

2.可以当做JSP小偷

3.可以当做全文网摘

package richin.reflect;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class PageStatic {
	public static void convert2Html(String sFilePath,String sSavePath,String sHtmlFile) throws IOException
	{
		PageStatic ru = new PageStatic(); 
		String baseHref="<base href='"+sFilePath+"'></base>";
		String filePath = ru.getClass().getResource("/richin/reflect/PageStatic.class").getPath().toString(); //取得项目根目录
		filePath = filePath.substring(1, filePath.indexOf("WEB-INF")); 
	
		int HttpResult; 
		String SavePath = filePath + sSavePath; //保存路径 
		URL url=new URL(sFilePath); 
		URLConnection urlconn=url.openConnection(); //抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接,通过在 URL 上调用 openConnection 方法创建连接对象 
		urlconn.addRequestProperty("Accept-Language", "zh-cn");
		urlconn.connect(); //使用 connect 方法建立到远程对象的实际连接 
		HttpURLConnection httpconn=(HttpURLConnection)urlconn; //每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络 

		HttpResult=httpconn.getResponseCode(); //getResponseCode可以从 HTTP 响应消息获取状态码 

		if(HttpResult!=HttpURLConnection.HTTP_OK) { 
		} else { 
			String charset=httpconn.getContentType();
			//System.out.println(charset);
			String charType=charset.substring(charset.lastIndexOf("=")+1);
			//System.out.println(charType);
			if("text/html".equals(charType))
				charType="GBK";
		InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(),charType); 
		BufferedReader in = new BufferedReader(isr); 
		String inputLine; 
		if(!SavePath.endsWith("/")) { 
		SavePath+="/"; 
		} 
		FileOutputStream fout = new FileOutputStream(SavePath+sHtmlFile); 
		while ((inputLine = in.readLine()) != null) 
		{ 
		//System.out.println(inputLine);
		if(inputLine.toLowerCase().equals("<head>"))
		inputLine=inputLine+System.getProperty("line.separator")+baseHref;//加入basehref
		inputLine=inputLine+System.getProperty("line.separator");  //换行
		fout.write(inputLine.getBytes()); 
		} 
		in.close(); 
		fout.close(); 
		} 

	}
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		convert2Html("http://www.51cto.com/art/200807/79080.htm","/","a4.htm"); 
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值