根据url获取网页内容

 PrintWriter out = null;
        out = response.getWriter();           
                 try{
            
            URL getUrl = new URL("http://www.kuaidi100.com/applyurl?key="+KEY+"&com="+com+"&nu="+nu);
            //System.out.println("getUrl:"+getUrl);
            // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
            // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) getUrl
            .openConnection();
            // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
            // 服务器
            connection.connect();
            // 取得输入流,并使用Reader读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));//设置编码,否则中文乱码
            String lines;
            while ((lines = reader.readLine()) != null){
                //lines = new String(lines.getBytes(), "utf-8");
                out.print(lines);//输出网页内容
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            out.close();
        }

 

posted @ 2013-11-07 10:12  Pioneerlug  阅读(442)  评论(0编辑  收藏  举报