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.

[more]

    private readonly string Url = "http://ec.europa.eu/taxation_customs/vies/cgi-bin/viesquer";
private readonly string Referer = "http://ec.europa.eu/taxation_customs/vies/en/vieshome.htm";
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);
newStream.Close();
HttpWebResponse resp = null;
try
     {
resp = (HttpWebResponse)myRequest.GetResponse();
}
catch (Exception ex)
{
Exceptions.Add(ex);
}
     StreamWriter myWriter = null;
try
     {
myWriter = new StreamWriter(resp.GetResponseStream());
myWriter.Write(data);
}
catch (Exception e)
{
Exceptions.Add(e);
return VatCheckOk.NotChecked;
}
finally
     {
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)myRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
string result = sr.ReadToEnd();
// Close and clean up the StreamReader
         sr.Close();
}
If i remember well, i used the result string to check for the string: "Yes, Valid number".
blog comments powered by Disqus

Who.I.am

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

Month List