一段将网页静态化的JAVA代码

不多说,直接看源代码,思路很简单,用URLConnection读取页面,然后保存就行了。

  1. import java.io.BufferedReader;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. /**
  9.  * 一段将网页静态化的代码。
  10.  * 
  11.  * @author 老紫竹 JAVA世纪网(java2000.net)
  12.  * 
  13.  */
  14. public class Test {
  15.   /**
  16.    * 将信息转化为静态html
  17.    * 
  18.    * @param sUrl
  19.    *          动态信息访问URL
  20.    * @param charset
  21.    *          编码类型
  22.    * @param sSavePath
  23.    *          存储为静态文件的目录
  24.    * @param sHtmlFile
  25.    *          生成的静态文件名,可以按信息的唯一ID+.html命名
  26.    * @throws IOException
  27.    */
  28.   public static void convert2Html(String sUrl, String charset,
  29.       String sSavePath, String sHtmlFile) throws IOException {
  30.     int HttpResult;
  31.     URL url = new URL(sUrl);
  32.     URLConnection urlconn = url.openConnection();
  33.     // 抽象类 URLConnection
  34.     // 是所有类的超类,它代表应用程序和 URL
  35.     // 之间的通信链接,通过在 URL 上调用
  36.     // openConnection 方法创建连接对象
  37.     urlconn.connect(); // 使用 connect 方法建立到远程对象的实际连接
  38.     HttpURLConnection httpconn = (HttpURLConnection) urlconn;
  39.     // 每个
  40.     // HttpURLConnection
  41.     // 实例都可用于生成单个请求,
  42.     // 但是其他实例可以透明地共享连接到
  43.     // HTTP 服务器的基础网络
  44.     HttpResult = httpconn.getResponseCode();
  45.     // getResponseCode可以从 HTTP
  46.     // 响应消息获取状态码
  47.     if (HttpResult != HttpURLConnection.HTTP_OK) {
  48.     } else {
  49.       InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(),
  50.           charset);
  51.       BufferedReader in = new BufferedReader(isr);
  52.       String inputLine;
  53.       if (!sSavePath.endsWith("/")) {
  54.         sSavePath += "/";
  55.       }
  56.       FileOutputStream fout = new FileOutputStream(sSavePath + sHtmlFile);
  57.       while ((inputLine = in.readLine()) != null) {
  58.         System.out.println(inputLine);
  59.         fout.write((inputLine+"\n").getBytes());
  60.       }
  61.       in.close();
  62.       fout.close();
  63.     }
  64.   }
  65.   public static void main(String[] args) throws IOException {
  66.     Test ru = new Test();
  67.     String filePath = ru.getClass().getResource(".").getPath().toString(); // 取得项目根目录
  68.     convert2Html("http://www.java2000.net/""UTF-8", filePath + "/",
  69.         "aaaa.htm");
  70.   }
  71. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值