HTTP Post in C# .Net

Why re-invent the wheel? 😉

See below for a few quick examples from the minds over at csharp-online and codeproject.


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All examples are in C# .Net.

HTTP Post:

using System.Net;
...
string HttpPost (string uri, string parameters)
{ 
   // parameters: name1=value1&name2=value2	
   WebRequest webRequest = WebRequest.Create (uri);
   //string ProxyString = 
   //   System.Configuration.ConfigurationManager.AppSettings
   //   [GetConfigKey("proxy")];
   //webRequest.Proxy = new WebProxy (ProxyString, true);
   //Commenting out above required change to App.Config
   webRequest.ContentType = "application/x-www-form-urlencoded";
   webRequest.Method = "POST";
   byte[] bytes = Encoding.ASCII.GetBytes (parameters);
   Stream os = null;
   try
   { // send the Post
      webRequest.ContentLength = bytes.Length;   //Count bytes to send
      os = webRequest.GetRequestStream();
      os.Write (bytes, 0, bytes.Length);         //Send it
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Request error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   finally
   {
      if (os != null)
      {
         os.Close();
      }
   }
 
   try
   { // get the response
      WebResponse webResponse = webRequest.GetResponse();
      if (webResponse == null) 
         { return null; }
      StreamReader sr = new StreamReader (webResponse.GetResponseStream());
      return sr.ReadToEnd ().Trim ();
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Response error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   return null;
} // end HttpPost 

Intermediate webrequest usage:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
 
namespace BaseClassNameSpace.Web.BaseServices
{

//This base class provides implementation of request 

//and response methods during Http Calls.
      public class HttpBaseClass
      {
 
            private string UserName;
            private string UserPwd;
            private string ProxyServer;
            private int ProxyPort;
            private string Request;
            
            public HttpBaseClass(string HttpUserName, 
              string HttpUserPwd, string HttpProxyServer, 
              int HttpProxyPort, string HttpRequest)
            {
                  UserName = HttpUserName;
                  UserPwd = HttpUserPwd;
                  ProxyServer = HttpProxyServer;
                  ProxyPort = HttpProxyPort;
                  Request = HttpRequest;
            }
 
/// <summary>

// This method creates secure/non secure web
// request based on the parameters passed.
            public virtual HttpWebRequest CreateWebRequest(string uri, 
              NameValueCollection collHeader, 
              string RequestMethod, bool NwCred)
            {
                  HttpWebRequest webrequest = 
                   (HttpWebRequest) WebRequest.Create(uri);
                  webrequest.KeepAlive = false;
                  webrequest.Method = RequestMethod;
 
                  int iCount = collHeader.Count;
                  string key;
                  string keyvalue;
 
                  for (int i=0; i < iCount; i++)
                  {
                        key = collHeader.Keys[i];
                        keyvalue = collHeader[i];
                        webrequest.Headers.Add(key, keyvalue);
                  }
                  
                  webrequest.ContentType = "text/html"; 
                  //"application/x-www-form-urlencoded";

                  if (ProxyServer.Length > 0)
                  {
                     webrequest.Proxy = new 
                      WebProxy(ProxyServer,ProxyPort);
                  }
                  webrequest.AllowAutoRedirect = false;
 
                  if (NwCred)
                  {
                      CredentialCache wrCache = 
                              new CredentialCache();
                      wrCache.Add(new Uri(uri),"Basic",
                        new NetworkCredential(UserName,UserPwd));
                      webrequest.Credentials = wrCache;
                  }
                  //Remove collection elements

                  collHeader.Clear();
                  return webrequest;
            }//End of secure CreateWebRequest

            
            // This method retreives redirected URL from

            // response header and also passes back

            // any cookie (if there is any)

            public virtual string GetRedirectURL(HttpWebResponse 
                 webresponse, ref string Cookie)
            {
                  string uri="";
 
                  WebHeaderCollection headers = webresponse.Headers;
                  
                  if ((webresponse.StatusCode == HttpStatusCode.Found) || 
                    (webresponse.StatusCode == HttpStatusCode.Redirect) ||
                    (webresponse.StatusCode == HttpStatusCode.Moved) ||
                    (webresponse.StatusCode == HttpStatusCode.MovedPermanently))
                  {
                        // Get redirected uri

                        uri = headers["Location"] ;
                        uri = uri.Trim();
                  }
 
                  //Check for any cookies

                  if (headers["Set-Cookie"] != null)
                  {
                        Cookie = headers["Set-Cookie"];  
                  }
                  //                string StartURI = "http:/";

//                if (uri.Length > 0 && uri.StartsWith(StartURI)==false)

//                {

//                      uri = StartURI + uri;

//                }

                  return uri;
            }//End of GetRedirectURL method

            public virtual string GetFinalResponse(string ReUri, 
             string Cookie, string RequestMethod, bool NwCred)
            {
                  NameValueCollection collHeader = 
                        new NameValueCollection();
 
                  if (Cookie.Length > 0)
                  {
                        collHeader.Add("Cookie",Cookie);
                  }
 
                  HttpWebRequest webrequest = 
                    CreateWebRequest(ReUri,collHeader, 
                    RequestMethod, NwCred);
                        
                  BuildReqStream(ref webrequest);
 
                  HttpWebResponse webresponse;
 
                  webresponse = (HttpWebResponse)webrequest.GetResponse();
 
                  Encoding enc = System.Text.Encoding.GetEncoding(1252);
                  StreamReader loResponseStream = new 
                    StreamReader(webresponse.GetResponseStream(),enc);
 
                  string Response = loResponseStream.ReadToEnd();
 
                  loResponseStream.Close();
                  webresponse.Close();
                  
                  return Response;
            }
 
            private void BuildReqStream(ref HttpWebRequest webrequest)
            {
                  byte[] bytes = Encoding.ASCII.GetBytes(Request);
                  webrequest.ContentLength=bytes.Length;
 
                  Stream oStreamOut = webrequest.GetRequestStream();
                  oStreamOut.Write(bytes,0,bytes.Length);
                  oStreamOut.Close();
            }
      }
}//End of HttpBaseClass class

References:
Csharp-online, “HTTP Post”, http://en.csharp-online.net/HTTP_Post
Codeproject, “How to use HttpWebRequest and HttpWebResponse in .NET”, http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx

Advertisement

About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on February 2, 2011, in Programming & Development and tagged , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: