How to fill forms and submit with Webclient in C#

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


Solution 1:

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

Solution 2:

Try this:

using System.Net;
using System.Collections.Specialized;  

NameValueCollection values = new NameValueCollection();
values.Add("TextBox1", "value1");
values.Add("TextBox2", "value2");
values.Add("TextBox3", "value3");
string Url = urlvalue.ToLower();

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    byte[] result = client.UploadValues(Url, "POST", values);
    string ResultAuthTicket = System.Text.Encoding.UTF8.GetString(result);
}

Solution 3:

I have found a solution to my problem. First of all I was confused about some of the basics in http-communication. This was caused by a python-script i wrote, which have a different approach with the communication.

I solved it with generating the POST-data from scratch and open the uri, which was contained in the form-action.