Http POST to webserver using C#

by Damiaan Peeters 6. March 2008 11:38

I 've written some time ago a HTML scraper to search the VIES VAT number Validation web site of the European Union.  The service offered no web service at that time, so I needed to use the HTTP POST method.

The code is not too difficult.


    private readonly string Url = "";
private readonly string Referer = "";
List<Exception> Exceptions = null;
     ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Lang=EN";
postData += ("&VAT=" + VatNumber);
postData += ("&MS=" + CountryCode);
postData += ("&ISO=" + CountryCode);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.Url);
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Referer = Referer;
myRequest.ContentLength = data.Length;
myRequest.ProtocolVersion = HttpVersion.Version10;
myRequest.Method = "POST";
Stream newStream = myRequest.GetRequestStream();
// Send the data.
     newStream.Write(data, 0, data.Length);
HttpWebResponse resp = null;
resp = (HttpWebResponse)myRequest.GetResponse();
catch (Exception ex)
     StreamWriter myWriter = null;
myWriter = new StreamWriter(resp.GetResponseStream());
catch (Exception e)
return VatCheckOk.NotChecked;
HttpWebResponse objResponse = (HttpWebResponse)myRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
string result = sr.ReadToEnd();
// Close and clean up the StreamReader
If i remember well, i used the result string to check for the string: "Yes, Valid number".

Certified Umbraco Master, Part of Umbraco Certified partner comm-it, .Net and Azure developer, seo lover. Magician in my spare time.

Month List