How to fill forms and submit with Webclient in C#
c#, webclient
Solution
You should probably be using `HttpWebRequest` for this. Here's a simple example:
var strId = UserId_TextBox.Text;
var strName = Name_TextBox.Text;
var encoding=new ASCIIEncoding();
var postData="userid="+strId;
postData += ("&username="+strName);
byte[] data = encoding.GetBytes(postData);
var myRequest =
(HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Default.aspx");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
var newStream=myRequest.GetRequestStream();
newStream.Write(data,0,data.Length);
newStream.Close();
var response = myRequest.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream);
var result = responseReader.ReadToEnd();
responseReader.Close();
response.Close();
Problem
I'm new at using the the libraries WebClient, HttpResponse and HttpRequest in C#, so bear with me, if my question is confusing to read. I need to build a WinForm based on C# which can open a URL, which is secured with the basic authorization. I did this with adding this to the header, like this: ``` using (WebClient wc = new WebClient()) { wc.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String( Encoding.ASCII.GetBytes(username + ":" + password))); } ``` So far, so good! Now I would like to fill a form with a number, and I find the source-code from the site, and discover that the name is "number". So I write this: ``` NameValueCollection formData = new NameValueCollection(); formData["number"] = number byte[] responseBytes = wc.UploadValues(theurl, "POST", formData); string response = Encoding.ASCII.GetString(responseBytes); textBox_HTML.Text = response; ``` But how do I submit this? I will like to receive my "search-results"...