Using C # data for HttpPost in a web page
I want to login to a site using C # code.
Here's the html code of the example:
<form action="http://www.site.com/login.php" method="post" name="login" id="login">
<table border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr><td><b>User:</b></td><td colspan=\"2\"><b>Password:</b></td></tr>
<tr>
<td><input class="inputbg" name="user" type="text"></td>
<td><input class="inputbg" name="password" type="password"></td>
<td><input type="submit" name="user_control" value="Submit" class="buttonbg"></td>
</tr>
</tbody></table>
</form>
This is what I have tried so far with unsuccessful results:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.site.com/login.php");
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("user=user&password=pass&user_control=Eingabe");
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
stream = new StreamWriter("login.html");
stream.Write(reader.ReadToEnd());
stream.Close();
}
Any ideas why this fails?
+2
a source to share
2 answers
Have a look at cookiecontainer .
Sites that use forms-based authentication generally rely on cookies. Without setting the request container cookie, it won't support cookies.
0
a source to share
I would suggest using Fiddler2 to see what exactly is the difference between POST and browser.
Also, I prefer to use the WebClient class as it is a nice om GET / POST abstraction and easy to use.
Sample code,
https://github.com/alexanderbeletsky/trackyt.api.csharp/blob/master/Trackyt.Api/Adapter/Adapter.cs
0
a source to share