使用C#WebClient伪造表单提交
我需要调用一个Web并从我的asp.net mvc应用程序中的模型中检索结果数据。 在Web上访问时,表单如下所示:
我需要将输入的数据传递给textarea id =“p”。 如何添加,使用WebClient连接?
谢谢!
编辑这不是出于测试目的,我需要检索数据以便在我的应用程序中使用。
我刚用过这个: http : //www.eggheadcafe.com/community/aspnet/2/69261/you-can-use-the-webclient.aspx
另一个选择是微软的轻量级测试自动化框架 < - 这里史蒂夫桑德森将其应用于MVC。
您创建一个Stream并将其传递给您的HttpWebRequest。
// 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 = "p=Some text here from the textarea"; 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 ();
这些东西习惯变得越来越复杂,例如你需要处理cookie,身份validation或多部分表单上传以上传文件等。我建议使用curl( http://sourceforge.net/projects/libcurl-net/ )
像这样的东西:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string data = "&p=" + dataThatNeedsToBeInTextArea; byte[] byteArray = Encoding.UTF8.GetBytes (data); req.ContentLength = byteArray.Length; Stream stream= req.GetRequestStream (); stream.Write (byteArray, 0, byteArray.Length); stream.Close (); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string response = streamIn.ReadToEnd(); streamIn .Close();
同意@wentbackward , WatiN是另一种选择。