簡體   English   中英

使用C#將數據發布到網頁上

[英]Using C# to HttpPost data to a web page

我想使用C#代碼登錄網站。

這是示例表單的html代碼:

<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>

到目前為止,這是我嘗試過但未成功的結果:

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();
}

任何想法,這為什么會失敗?

查看cookiecontainer

使用基於表單的身份驗證的網站通常依賴Cookie。 如果不設置請求的cookiecontainer,它將不支持cookie。

我建議使用Fiddler2來查看瀏覽器的POST和應用程序的POST之間的確切區別。

另外,我更喜歡使用WebClient類,因為它是GET / POST的很好的抽象並且易於使用。

代碼示例

https://github.com/alexanderbeletsky/trackyt.api.csharp/blob/master/Trackyt.Api/Adapter/Adapter.cs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM