c# - 如何使用 FormUrlEncodedContent 在 c# 中发布 http 请求
问题描述
我想发布一个 http 请求,以便使用 HttpClient 和 FormUrlEncodedContent 登录网站。我可以跟踪响应在我的 chrome 浏览器上的外观,但是当我重新创建浏览器发出的发布请求时,我没有得到预期的响应。我尝试登录的网站是https://www.lectio.dk/lectio/31/login.aspx。
我想我对应该为 FormUrlEncodedContent 提供什么有疑问(使用 chrome 中的网络选项卡,我可以看到请求标头和表单数据,但是如何选择应该提供的内容?)。目前我的代码看起来像这样。
CookieContainer container = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = container;
HttpClient client = new HttpClient(handler);
Console.WriteLine(client.DefaultRequestHeaders + "\n" + "--------------------------");
Dictionary<string, string> vals = new Dictionary<string, string>
{
{"user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"},
{"accept-language","en-GB,en-AS;q=0.9,en-DK;q=0.8,en;q=0.7,da-DK;q=0.6,da;q=0.5,en-US;q=0.4"},
{"accept-encoding","gzip, deflate, br"},
{"accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"},
{"m$Content$username2","username"},
{"m$Content$passwordHidden","password"},
{"__EVENTTARGET","m$Content$submitbtn2"},
};
FormUrlEncodedContent content = new FormUrlEncodedContent(vals);
var response = client.PostAsync("https://www.lectio.dk/lectio/31/login.aspx", content);
var responseString = response.Result;
Console.WriteLine(responseString);
handler.Dispose();
client.Dispose();
这个想法是登录到网站(我想我的 Cookiecontainer 会处理这个问题?),这样我就可以抓取 som 数据。
解决方案
推荐阅读
- ruby-on-rails - 删除多个图像活动存储阵列中的单个图像
- java - 我如何使用 usb4java 获取设备的字符串路径?
- javascript - 如何访问 json 对象
- visual-studio-code - VSCode:如何在另一个窗格中打开文档(ala `show hover`)?
- html - 名称和消息上下并与图标对齐
- sql-server - 无法更改 SQL 中的默认用户语言
- sql-server - 使用 SQL INSERT 从两个列表中插入多条记录
- r - 如何将用户ID转换为R中的整数?
- xml - TestNG 参数 - 如何同时运行多个测试用例
- re - 查找最长的重复子序列