是否可以将基于窗口的应用程序中的某些数据发布到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网站并在TextArea中获取html数据。 GetPageHtml()
函数获取html数据。但主要问题是发布登录详细信息不起作用,我的意思是无法登录xyz.com
答案 0 :(得分:1)
一旦登录结果返回,它就会有一个cookie(假设这是一个经过Forms认证的站点)。然后,您需要获取该cookie并在发布到受保护页面时使用该cookie。否则,它将如何知道您已通过身份验证?
答案 1 :(得分:1)
如果该网站使用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);
}
}
}