Akismet.NET.Validator.PostRequest C# (CSharp) Method

PostRequest() protected method

Post parameters to the input url and return the response.
protected PostRequest ( String url, NameValueCollection pars ) : String
url String The input url (absolute).
pars System.Collections.Specialized.NameValueCollection The input parameters to send.
return String
        protected virtual String PostRequest(String url, NameValueCollection pars)
        {
            // check input data
            if (String.IsNullOrEmpty(url) || !Uri.IsWellFormedUriString(url, UriKind.Absolute) || (null == pars))
                return String.Empty;

            String content = String.Empty;
            // create content for the post request
            foreach (String key in pars.AllKeys)
            {
                if (String.IsNullOrEmpty(content))
                    content = String.Format("{0}={1}", key, pars[key]);
                else
                    content += String.Format("&{0}={1}", key, pars[key]);
            }

            // initialize request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = content.Length;
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.UserAgent = "Akismet.NET";

            StreamWriter writer = null;
            try
            {
                // write request content
                writer = new StreamWriter(request.GetRequestStream());
                writer.Write(content);
            }
            catch (Exception)
            { // return failure
                return String.Empty;
            }
            finally
            { // close the writer, if any
                if (null != writer)
                    writer.Close();
            }

            // retrieve the response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                // retrieve response
                String result = reader.ReadToEnd();

                // close the reader
                reader.Close();

                // return result
                return result;
            }
        }