我尝试使用c#webclient登录论坛以获取用户相关信息 我的问题是登录失败 我试图通过邮件提交所有需要的数据
我的实际代码:
var url = new Uri("http://www.hardwareluxx.de/community/");
string user = Properties.Resources.username;
string pass = Properties.Resources.password;
var client = new CookieAwareWebClient();
client.BaseAddress = @"http://www.hardwareluxx.de/community/";
var document = new HtmlDocument();
document.Load(new MemoryStream(client.DownloadData("index.php")));
postData = new NameValueCollection();
postData.Add("vb_login_username", user);
postData.Add("cookieuser", "1");
postData.Add("vb_login_password", "");
postData.Add("s", "");
postData.Add("securitytoken", "guest");
postData.Add("do", "login");
postData.Add("vb_login_md5password", GetMd5Hash(pass));
postData.Add("vb_login_md5password_utf", GetMd5Hash(pass));
document.Load(new MemoryStream(client.UploadValues(url + "login.php?do=login", postData)));
和一个小的帮助方法来获取登录所需的md5哈希:
public static string GetMd5Hash(string TextToHash)
{
//Prüfen ob Daten übergeben wurden.
if (string.IsNullOrEmpty(TextToHash))
{
return string.Empty;
}
//MD5 Hash aus dem String berechnen. Dazu muss der string in ein Byte[]
//zerlegt werden. Danach muss das Resultat wieder zurück in ein string.
MD5 md5 = new MD5CryptoServiceProvider();
byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
byte[] result = md5.ComputeHash(textToHash);
return BitConverter.ToString(result);
}
以及存储cookie的webclient:
public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer _cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = _cookie;
}
return request;
}
}
答案 0 :(得分:0)
您应该使用request.Credentials
将凭据传递给HttpWebRequest实例public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer _cookie = new CookieContainer();
private string userName;
private string password;
public CookieAwareWebClient(string user, string pass)
{
userName = user;
password = pass;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (!string.IsNullOrEmpty(userName))
{
request.Credentials = new NetworkCredential(userName, password);
}
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = _cookie;
}
return request;
}
}
string user = Properties.Resources.username;
string pass = Properties.Resources.password;
var client = new CookieAwareWebClient(user, pass);