实现HttpServlet HttpURLConnect获取页面

1.模拟浏览器获取http://www.51job.com的流

2.将获取的流用resp.writ() 写入到resp中

3.浏览器输入localhost:8080将会看到51job的界面。

public class ServletDem extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*

        System.out.println(req.getContextPath());
        System.out.println(req.getHeaderNames());
        System.out.println(req.getHeader("Accept"));
      //  System.out.println(req.getHeader(req.getQueryString()));
        System.out.println("req.getRemoteHost()"+req.getRemoteHost());
        System.out.println("端口号"+req.getRemotePort());
        System.out.println("URI"+req.getRequestURI());
        */
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        resp.setCharacterEncoding("Unicode");
        String s0 = new String(req.getRequestURL());

        if(!s0.equals("http://detectportal.firefox.com/success.txt")){
            System.out.println(df.format(date)+":get");
            System.out.println(s0);
        }

        //获取51job html页面
        HttpURLConnection hr = null;
        URL url = new URL("https://ai.baidu.com/");
        hr = (HttpURLConnection) url.openConnection();
        hr.setRequestProperty("accept", "*/*");
        hr.setRequestProperty("connection", "Keep-Alive");
        hr.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");

        hr.connect();
        InputStream is = hr.getInputStream();
        StringBuilder sb = new StringBuilder();
        byte[] b =is.readAllBytes();

        hr.disconnect();
        is.close();

        ServletOutputStream sos = resp.getOutputStream();
        sos.write(b);
        
    }


}
View Code

 

转载于:https://www.cnblogs.com/wangge01/p/9501367.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值