c# - 如何在 C# 中发出 http 请求并获得响应

标签 c# http post

<分区>

假设我有一个网页提示输入然后在数据库中搜索用户的用户名和密码,然后解密密码并检查输入的密码是否与数据库中的用户密码相同。如果我想将登录切换到 C# winforms 应用程序怎么办?我如何使用用户名和输入的密码发出该 http 请求,然后让网站接受用户名/密码字符串并按照我之前所说的相同方式在数据库中搜索这些字符串,然后发送一个 bool of true:用户输入了正确的信息或false:用户输入的信息不正确。我怎么能那样做?

最佳答案

首先要知道服务器是如何接受请求的,最有可能是post方法,因为你必须输入用户名和密码,然后你必须得到输入的字符串,可以得到用一个 一些浏览器扩展,例如 Live Http Headers . 它应该看起来像这样

http://yourwebsite/extension

POST /extension HTTP/1.1
Host: yourwebsite
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Length: 85
Content-Type: application/x-www-form-urlencoded
Connection: keep-alive
HereShouldBeThePoststring

然后您将使用网站 url 创建一个 httpwebrequest

            using System.Net;
            string postUrl = "YourWebsiteUrlWithYourExtension";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);

然后你会发布你的数据

  string postString = "ThePostStringYouObtainedUsingLiveHttpHeaders";
            request.Method = "POST";
            byte[] Content = Encoding.ASCII.GetBytes(postString);
            request.ContentLength = Content.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.W

然后你会得到响应字符串

 string responsestring = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responsestring = reader.ReadToEnd();
            }

然后您将解析您的字符串以获取您需要的数据。 一个好的解析库是 Html Agility Pack .

关于c# - 如何在 C# 中发出 http 请求并获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421822/

相关文章:

http - 我无法使用 YouTube Data API v3 获取 channel ID

javascript - 将 HTML 表单转换为 Angular POST 请求

c# - HttpWebRequest 响应生成 HTTP 422。为什么?

python - 如何从 suds 请求中获取响应 header

c# - 使用什么来代替 C# 事件以使代码易于移植到 C++?

c# - 每个继承类类型的继承静态成员都不同?

c# - 如何使用动态类型获取数组大小

json - 如何为 JBoss 配置 Gzip?

http - "Maximum number of POST request parameters"限制是可捕获的吗?

c# - 将 XAML 中 WPF 窗口的启动位置更改为右下角