简体   繁体   English

HttpWebRequest和HttpWebResponse

[英]HttpWebRequest and HttpWebResponse

I`m building an application that need to authenticate session on a website and then submits/retrieved data. 我正在构建一个需要对网站上的会话进行身份验证然后提交/检索数据的应用程序。

This is what I`ve been able to do till now (through googling). 这是我到目前为止(通过谷歌搜索)能够做的。 I`ve been able to detect if the requested page actually exists or not, but more than that, I couldn`t proceed! 我已经能够检测出所请求的页面是否确实存在,但除此之外,我无法继续!

WebRequest request = WebRequest.Create("http://localhost/");
try
{
    using (WebResponse response = request.GetResponse())
    {
        HttpWebResponse httpResponse = (HttpWebResponse)response;
        textBlock1.Text = "Connected ...\n Status code is: " + httpResponse.StatusCode;
    }
}
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse)response;
        textBlock1.Text = "Error Code: " + httpResponse.StatusCode;
    }
}

This code just detects if the web source requested exists or not. 此代码仅检测所请求的Web源是否存在。 Now I`ll assume that the source exists, how can I send username/password to be authenticated? 现在,我假设源存在,如何发送要验证的用户名/密码?

I`ll assume that the username/password fields are named user/pass simultaneously ... How can I send the username and password to the website to validate and read the response? 我将假定用户名/密码字段同时命名为用户/密码...如何将用户名和密码发送到网站以验证和读取响应?

I believe that this part will be very helpful throughout the whole development process. 我相信这部分将在整个开发过程中非常有帮助。

Have a look at this SO question (and answers): Login and retrieve data from embedded form page using C# 看看这个SO问题(和答案): 使用C#登录并从嵌入式表单页面检索数据

You only need to adjust the names of the form fields accordingly to your target site. 您只需要根据目标站点调整表单字段的名称即可。

There is a Credentials property for the WebRequest object which you can use to send along with the request. WebRequest对象有一个凭据属性,可用于与请求一起发送。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url-here");
request.Credentials = new NetworkCredential("username", "password");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM