Java 利用 HttpURLConnection 读取页面 返回字节流(生成静态页面)

               

注:若需要被静态化的 页面中 使用了 response.sendRedirect跳转,则最后静态页面为 最终跳转后的页面。

而那些 使用js 跳转的 比如 window.location.href 则 无效,直接作为js代码在生成的静态页面中,并执行。

//保存为文件
import java.io.*;public class GenerateIndexPage {  protected static String defaultToFile = "frame/main_Null.html"protected static String defaultFromFile = "http://localhost:8080/stfb/frame/main_Null.jsp";    String result = "";  public String genHtml(String fromFile,String toFile) throws Exception {  if("".equals(fromFile)||fromFile==null){   fromFile = defaultFromFile;  }  if("".equals(toFile)||toFile==null){   toFile = defaultToFile;  }  java.net.URL url = new java.net.URL(fromFile);  java.net.HttpURLConnection conn =(java.net.HttpURLConnection) url.openConnection();  try{   if (conn.getResponseCode() == 200) {       java.io.InputStream is = (java.io.InputStream) conn.getContent();    try{     ConfigInfo cfn = new ConfigInfo();     String server_path = cfn.getValue("server_path");     String savePath = server_path+"\\"+toFile;     FileOutputStream baos = new FileOutputStream(new File(savePath));     int buffer = 1024;     byte[] b = new byte[buffer];     int n = 0;     while ((n = is.read(b, 0, buffer)) > 0) {      baos.write(b, 0, n);     }     //String s = new String(baos.toByteArray(), WEATHER_HTML_CHARSET);     is.close();     baos.close();     result = "生成成功";    }catch(Exception e){     result="写文件过程出错,取消生成。";    }   }else{    result="获得链接过程出错,取消生成。";      }  }catch(Exception e){    e.printStackTrace();    result="获得内容过程出错,取消生成。";  }  return result; }  }


//返回字节流

public String getHtml(JspWriter out) throws Exception //System.setProperty("http.proxyHost", "isaserver");System.setProperty("http.proxyPort", "80"); java.net.URL url = new java.net.URL("http://weather.china.com.cn/city/58362_zx.html"); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection(); if (conn.getResponseCode() == 200) {  java.io.InputStream is = (java.io.InputStream) conn.getContent();  java.io.ByteArrayOutputStream baos =    new java.io.ByteArrayOutputStream();    int buffer = 1024;  byte[] b = new byte[buffer];  int n = 0;  while ((n = is.read(b, 0, buffer)) > 0) {   baos.write(b, 0, n);  }  String s = new String(baos.toByteArray(), "UTF-8");  is.close();  baos.close();  return s; } return "";}



           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值