NerdyHearn
Home
Blog
Software

Contact
Mailing List

IPhone Products
SMS To Gmail
Voicemail To Gmail
Calls To Calendar

Other Products
TiffWizard

Sites
SaveMySerials
How Long For Me
DocuTerminal

Blog
Twitter

NerdyHearn - Blog


<< Back To All Blogs

Creating a reusable web client for PUT, POST, and DELETE in C#

Thursday, July 23rd, 2009

C# has a very basic and pretty easy-to-understand methodology for sending and receiving web requests, but seeing as I use this type of operation on a regular basis it has served me very well over the years to have my own class that I have added to as needed. I figured I would share this with those of you interested in the hope that it would make your lives easier as well.

This class works very easily, allowing a user to specify the parameters, timeout, and user agent as required, and PUT, POST, or DELETE methods to
execute web requests as necessary. Each request returns an HttpResult class which includes the response code, as well as the data returned.

Without further ado, here is the code:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;



namespace NerdyHearn.Com

{

    public class HttpResult

    {

        private string m_Data = string.Empty;

        private System.Net.HttpStatusCode m_StatusCode = System.Net.HttpStatusCode.OK;



        public HttpResult(string Data, System.Net.HttpStatusCode StatusCode)

        {

            m_Data = Data;

            m_StatusCode = StatusCode;

        }



        public string Data

        {

            get

            {

                return m_Data;

            }

        }



        public System.Net.HttpStatusCode StatusCode

        {

            get

            {

                return m_StatusCode;

            }

        }

    }



    public class HttpRequest

    {

        private string m_URL = string.Empty;

        private string m_UserAgent = string.Empty;

        private Dictionary<string, string> m_Parameters = new Dictionary<string, string>();

        private int m_Timeout = 60000;



        public HttpRequest() { }



        public HttpResult Send(string Method)

        {

            string qString = string.Empty;



            if (Parameters.Count > 0)

            {

                foreach (string key in Parameters.Keys)

                {

                    if (!qString.Equals(""))

                    {

                        qString += "&";

                    }

                    qString += key + "=" + System.Web.HttpUtility.UrlEncode(Parameters[key].ToString());

                }

            }



            WebRequest request = WebRequest.Create(m_URL);

            if (!m_UserAgent.Equals(""))

            {

                ((HttpWebRequest)request).UserAgent = m_UserAgent;

            }

            request.Method = Method;

            request.Timeout = m_Timeout;



            if (Method.Equals("POST") || Method.Equals("DELETE"))

            {

                byte[] byteArray = Encoding.UTF8.GetBytes(qString);

                request.ContentType = "application/x-www-form-urlencoded";

                request.ContentLength = byteArray.Length;

                Stream dataStreamPostData = request.GetRequestStream();

                dataStreamPostData.Write(byteArray, 0, byteArray.Length);

                dataStreamPostData.Close();

            }

            else if (Method.Equals("GET"))

            {

                m_URL += "?" + qString;

            }



            HttpStatusCode StatusCode = HttpStatusCode.OK;

            HttpWebResponse response;

            Stream dataStream;

            StreamReader reader;

            string result = string.Empty;



            response = (HttpWebResponse)request.GetResponse();

            StatusCode = response.StatusCode;

            dataStream = response.GetResponseStream();

            reader = new StreamReader(dataStream);

            result = reader.ReadToEnd();

            reader.Close();

            dataStream.Close();

            response.Close();

            return new HttpResult(result, StatusCode);

        }



        public string URL

        {

            get

            {

                return m_URL;

            }

            set

            {

                m_URL = value;

            }

        }



        public Dictionary<string, string> Parameters

        {

            get

            {

                return m_Parameters;

            }

            set

            {

                m_Parameters = value;

            }

        }



        public int Timeout

        {

            get

            {

                return m_Timeout;

            }

            set

            {

                m_Timeout = value;

            }

        }



        public string UserAgent

        {

            get

            {

                return m_UserAgent;

            }

            set

            {

                m_UserAgent = value;

            }

        }

    }

}


Pretty basic, but I love to have reusable code classes around to speed up development as much as possible.

WebRequestin' Tom Out.

Tags

CSharp

Related Blogs

Using MOSS and WSS SharePoint Workflow to Resize Images in an Image Library
Creating an Organizational Chart using C#: Part 1
Fixing "Error in loading DLL" in SharePoint
Reading a Microsoft Project file (mpp) in C#
Validate a Windows Username and Password against Active Directory

Comments

Currently no comments.

Add A Comment

Name:


URL:


Email Address: (not public, used to send notifications on further comments)


Comments:



Enter the text above, except for the 1st and last character:


NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. DocuTerminal - Online Filing Cabinet solution. Scan, search and archive your paper documents. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers SubSonos - Stream your subsonic music collection to your Sonos wireless system