HttpWebRequest使用的注意事项


        private void button33_Click(object sender, EventArgs e)

        {

   //下面这一步应该没有去连接远程服务器,因为地址如果错误,这一步没有出现异常

              HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://localhost:8081/weixin01/servlet/CoreServlet");
                hwr.CookieContainer = cc;
                hwr.ContentType = "application/x-www-form-urlencoded";
                hwr.Method = "POST";
                hwr.Timeout = 30 * 1000;
                hwr.KeepAlive = true;
                hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; BTRS124342; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)";
                hwr.Referer = "http://localhost:8080/weixin01/servlet/CoreServlet";
                Encoding encoding = Encoding.GetEncoding("utf-8");

                byte[] data = encoding.GetBytes("a=1");


//测试证明这一步会连接远程服务器,如果地址簿存存在,会报无法连接远程服务器的异常

                Stream myRequestStream = hwr.GetRequestStream();
            
                myRequestStream.Write(data, 0, data.Length);
                myRequestStream.Close();

          

 //测试证明在执行到下面红色这一行时候才会跳转到服务端后台的doPost方法之中

                HttpWebResponse myHttpWebResponse = (HttpWebResponse)hwr.GetResponse();
         
                Stream myResponseStream = myHttpWebResponse.GetResponseStream();
        
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gbk"));
          
                string outhtml = myStreamReader.ReadToEnd();
                //把数据从HttpWebResponse的Response流中读出
                myStreamReader.Close();
                myResponseStream.Close();
                myHttpWebResponse.Close();  
        }


你可能感兴趣的:(HttpWebRequest使用的注意事项)