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

posted @ 2019-06-23 15:46  江期玉  阅读(1900)  评论(0编辑  收藏  举报