Just Code‎ > ‎

C# get web page from code, POST and GET versions. Trying to get user agent to work...

posted Dec 17, 2009, 1:22 AM by Peter Henell
protected void GetPage_WithGet(string strURL)
        {
            //string strURL;
            string strResult;
            WebRequest wbrq = WebRequest.Create(strURL);
            wbrq.Credentials = CredentialCache.DefaultNetworkCredentials;
            wbrq.Headers["UserAgent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            //wbrq.Headers.Add(HttpRequestHeader.UserAgent, ");
            wbrq.Proxy = new WebProxy("http....", false, "localhost,127.0.0.1".Split(','), CredentialCache.DefaultNetworkCredentials);
            //wbrq.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            
            WebResponse wbrs;
            StreamReader sr;
            
            wbrq.Method = "GET";
            wbrs = wbrq.GetResponse();
            sr = new StreamReader(wbrs.GetResponseStream());
            strResult = sr.ReadToEnd().Trim();
            sr.Close();
            //  Write the returned data out to the page
            Console.WriteLine(strResult);
        
        }

        protected void GetPage_WithPost(string strURL)
        {
            ////string strURL = "";
            //string strPostData = "";
            //string strResult = "";
            //WebRequest wbrq;
            //WebResponse wbrs;
            //StreamWriter sw;
            //StreamReader sr;
            ////  Set the URL to post to
            ////strURL = "http://www.webcom.com/cgi-bin/form";
            //strPostData = string.Format("your_name={0}&userid={1}&form_name={2}", "Mark Smith", "webcom", "tutortest");
            ////  Create the web request
            //wbrq = WebRequest.Create(strURL);
            //wbrq.Method = "POST";
            //wbrq.Referer = "http://www.webcom.com/cgi-bin/form";
            //wbrq.ContentLength = strPostData.Length;
            //wbrq.ContentType = "application/x-www-form-urlencoded";
            //sw = new StreamWriter(wbrq.GetRequestStream);
            //sw.Write(strPostData);
            //sw.Close();
            ////  Read the returned data 
            //wbrs = wbrq.GetResponse;
            //sr = new StreamReader(wbrs.GetResponseStream);
            //strResult = sr.ReadToEnd.Trim;
            //sr.Close();
            ////  Write the returned data out to the page
            //TextBox1.Text = strResult;
        }
Comments