본문 바로가기

C#(ASP.NET)

WebRequest를 이용하여 웹 소스 가져오기


        protected void Page_Load(object sender, EventArgs e)
        {
            //주소를 가지고 초기화를 시켜줍니다.
            WebRequest req = WebRequest.Create("http://www.daum.net/");

            //인터넷 주소에 대한 응답을 반환합니다.
            WebResponse result = req.GetResponse();

            //인코딩설정
            Encoding encode = System.Text.Encoding.Default;

            //스트림설정
            Stream ReceiveStream = result.GetResponseStream();
            StringBuilder WebSouce = new StringBuilder();

            Byte[] read = new Byte[512];
            int bytes = ReceiveStream.Read(read, 0, 512);

            while (bytes > 0)
            {
                WebSouce.Append(encode.GetString(read, 0, bytes));
                bytes = ReceiveStream.Read(read, 0, 512);
            }
            ReceiveStream.Close();

            Response.Write(WebSouce.ToString());
        }


[출처] http://www.hoons.kr/Lecture/LectureView.aspx?BoardIdx=32&kind=26