zoukankan      html  css  js  c++  java
  • Java模拟http请求

    方法1:利用URLConnection获取页面利用response转发到自己网页

        public void index(HttpServletResponse response) throws IOException
        {
             /** 
             * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using 
             *  java.net.URL and //java.net.URLConnection 
             */  
            URL url;
            StringBuilder sb = new StringBuilder() ;
            String encoding = "utf-8";
            try {
                
                url = new URL("http://v.baidu.com");
                URLConnection conn = url.openConnection();
                if(conn.getContentEncoding()!=null)
                    encoding = conn.getContentEncoding();
                try(InputStream raw = conn.getInputStream()){//自动关闭
                    InputStream buffer = new BufferedInputStream(raw);
                    Reader reader = new InputStreamReader(buffer,encoding);
                    int c;
                    while((c=reader.read())!=-1) {
                        sb.append((char)c);
                    }
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
             response.setCharacterEncoding(encoding);
             response.setContentType("text/html");
             PrintWriter out = response.getWriter();
             out.println(sb);
             out.flush();
          
            return ;
        }

    方法2:利用httpclient

  • 相关阅读:
    2019-9-2-win10-uwp-Markdown
    2018-8-10-控件
    2018-8-10-win10-uwp-dataGrid
    2018-2-13-win10-uwp-hashcash
    2018-2-13-git-cannot-lock-ref
    UCOSIII系统内部任务
    UCOSIII时间片轮转调度
    Keil MDK fromelf生成bin文件
    UCOS内存管理
    uavcan扩展帧格式 zubax
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11073046.html
Copyright © 2011-2022 走看看