我尝试使用 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 的网络客户端:
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;
}
}