代码之家  ›  专栏  ›  技术社区  ›  FosterZ

使用C Sharp中的Windows窗体通过编程方式发布窗体

c#
  •  1
  • FosterZ  · 技术社区  · 14 年前

    是否可以将一些数据从基于窗口的应用程序发布到Web服务器?让我们务实点

    ASCIIEncoding encodedText = new ASCIIEncoding();
    string postData = string.Format("txtUserID={0}&txtPassword={1}", txtUName.Text, txtPassword.Text);
    byte[] data = encodedText.GetBytes(postData);
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.aimlifes.com/office/Login.aspx");
    webRequest.Method = "POST";
    webRequest.ContentType = "text/html";
    webRequest.ContentLength = data.Length;
    Stream strm = webRequest.GetRequestStream();
    strm.Write(data, 0, data.Length);
    
    txtUrlData.Text = GetPageHtml("http://www.aimlifes.com/office/ReceiveRecharge.aspx");
    
    strm.Close();
    

    GetPageHTML函数:

    public string  GetPageHtml(String Url)
    {
      WebClient wbc = new WebClient();
      return new System.Text.UTF8Encoding().GetString(wbc.DownloadData(Url));
    }
    

    我尝试的是使用给定的凭证登录xyz.com网站,并在文本区域中获取HTML数据。 GetPageHtml() 函数fetch是HTML数据。但主要问题是发布登录详细信息不起作用,我的意思是无法登录xyz.com。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Darin Dimitrov    14 年前

    如果站点使用cookie来添加经过身份验证的用户,您可以尝试以下操作:

    public class CookieAwareWebClient : WebClient
    {
        public CookieAwareWebClient ()
        {
            CookieContainer = new CookieContainer();
        }
    
        public CookieContainer CookieContainer { get; set; }
    
        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            ((HttpWebRequest)request).CookieContainer = CookieContainer;
            return request;
        }
    }
    
    public class Program
    {
        static void Main()
        {
            using (var client = new CookieAwareWebClient())
            {
                var values = new NameValueCollection
                {
                    { "txtUserID", "foo" },
                    { "txtPassword", "secret" }
                };
                // Authenticate. As we are using a cookie container
                // the user will be authenticated on the next requests
                // using this client
                client.UploadValues("http://www.aimlifes.com/office/Login.aspx", values);
    
                // The user is now authenticated:
                var result = client.DownloadString("http://www.aimlifes.com/office/ReceiveRecharge.aspx");
                Console.WriteLine(result);
            }
        }
    }
    
        2
  •  1
  •   Jerod Venema    14 年前

    一旦登录的结果返回,它将拥有一个cookie(假设这是一个经过表单验证的站点)。然后,您需要获取该cookie,并在发布到受保护的页面时使用它。否则,它怎么知道你已经认证了?