2010-09-17 19 views
1

是否可以將基於窗口的應用程序的某些數據發佈到Web服務器?讓實用通過編程方式在C sharp中使用Windows窗體發佈表單

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網站,並在一個TextArea獲取的HTML數據。函數獲取html數據。但主要問題是發佈登錄細節不起作用,我的意思是m無法登錄到xyz.com

回答

1

如果網站利用cookies來釘身份驗證的用戶,你可以試試這個:

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); 
     } 
    } 
} 
+0

嗨,它不工作,m仍然沒有得到認證,即變量

result
獲取Login.aspx頁面的數據,即它沒有驗證 – FosterZ 2010-09-20 06:52:03

1

一旦登錄結果返回,它會有一個cookie(假設這是一個cookie表單認證的網站)。然後,您需要獲取該cookie並在發佈到受保護頁面時使用該cookie。否則,它將如何知道您已通過身份驗證?

+0

對不起,我遲到評論,實際上是網站米試着訪問是簡單的ASP,所以表單身份驗證是在ASP。網絡權利? – FosterZ 2010-09-20 05:45:06

+1

不,表單認證基本上都是基於cookie的認證。 PHP/ASP/ASP.NET,無所謂。您仍然會有一些cookie從初始登錄時以您的身份驗證令牌返回,您需要在將來的請求中包含該cookie。 – jvenema 2010-09-20 12:20:24

相關問題