HttpWebRequest、HttpWebResponse简单Demo

HttpWebRequest 和HttpWebRespons 可以模拟浏览器的行为,对Web进行请求与提交,非常有用,我这里就把自己写的简单的例子收藏在这里

 

        /// <summary>

        /// 创建一个随机IP

        /// </summary>

        /// <returns>符合IP标准的一个IP值</returns>

        private string GetIP()

        {

            Random random = new Random(DateTime.Now.Millisecond + DateTime.Now.Second * 1000 + DateTime.Now.Minute * 10000 + DateTime.Now.Hour * 100000);

            random.Next(1, 254);

            string ip = random.Next(1, 254) + "." + random.Next(1, 254) + "." + random.Next(1, 254) + "." + random.Next(1, 254);

            return ip;



        }

        /// <summary>

        /// 对一个页面进行数据发送,并返回发送后的结果

        /// </summary>

        protected void PostRequest()

        {

            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://env.people.com.cn/GB/10725630.html");



            string strIPNew = GetIP();

            //内容可以使用HttpWatch 或者 FireBug 把Post的内容复制粘贴到这里

            byte[] btContent = Encoding.ASCII.GetBytes("内容");



            //使用Create来创建HttpWebRequest ,一般不要使用new

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://XXXXX/index.aspx");;

            // 如果接收方使用 string IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 来获取IP,就可以伪造IP地址信息

            request.Headers.Add("X_FORWARDED_FOR", strIPNew);

            //这里使用Post方式

            request.Method = "POST";

            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            request.ContentType = "application/x-www-form-urlencoded;charset=gb2312";

            request.ContentLength = btContent.Length;









            //把要Post的内容使用流写入

            using (Stream stream = request.GetRequestStream())

            {

                stream.Write(btContent, 0, btContent.Length);

            }

            //获取返回值

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

            {

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))

                {

                    string strContent = reader.ReadToEnd();

                    Response.Write(strContent);

                }

            }

        }

你可能感兴趣的:(response)