【发布时间】:2010-05-19 04:23:12
【问题描述】:
我不熟悉 http 的东西,但我如何能够向网站提交数据?我想从控制台应用程序“按下”一个提交按钮。这不是我自己的网站。
这是页面来源的一部分,不确定是否有任何相关性:
<form action="rate.php" method="post">
查看了 HttpWebRequest 类,但不熟悉需要填写哪些属性。
对不起,我含糊不清,但我对http不熟悉。
【问题讨论】:
我不熟悉 http 的东西,但我如何能够向网站提交数据?我想从控制台应用程序“按下”一个提交按钮。这不是我自己的网站。
这是页面来源的一部分,不确定是否有任何相关性:
<form action="rate.php" method="post">
查看了 HttpWebRequest 类,但不熟悉需要填写哪些属性。
对不起,我含糊不清,但我对http不熟悉。
【问题讨论】:
这是来自 MSDN 的 c/p。
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
这个过程非常简单,但您需要首先弄清楚您需要发送什么以及任何其他可能需要的特殊编码/cookies/等。我建议您对 Firefox 使用 Fiddler 和/或 Firebug。您可以通过网页查看工作请求中发生的一切,然后您可以在应用中模仿相同的行为。
【讨论】:
你可以看看codeprojectHttpWebRequest/Response in a nutshell - Part 1
【讨论】:
可以在此处找到一个灵活且易于使用的示例:C# File Upload with form fields, cookies and headers
【讨论】:
Response.Write("hello!");
Response.End();
【讨论】: