首页 > 解决方案 > 如何使用 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 数据。

标签: c#http

解决方案


推荐阅读