by
7,382 32
0
8
6,115
9
Top 1% !
Popular
Famous
Pearl of Wisdom
Tagged
Specified
Refined
OpenSource
Popularity: 1124th place
Created
Modified Sep 18, 2013

Published on:

.NETFramework4.0
Architecturex86_64
Extension.cs
InputName0serviceUrl
InputName1data
InputName2isPost
InputType0string
InputType1string
InputType2bool
LanguageCSharp
LicenseMIT_X11
MethodNameSendRequest
OSWindows
OutputTypestring
Windows VersionWindows7

Send an HTTP Request in C#

This is a core method to send an HTTP Request in C#.
It is able to store and re-use the set of cookies used in the past calls.
It makes use of log4net library to log information regarding the process.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11203/Send-an-HTTP-Request-in-C-?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
private CookieContainer m_cookies = new CookieContainer(); public string SendRequest(string serviceUrl, string data, bool isPost) { HttpWebRequest webRequest = null; log.DebugFormat("Creating request {0}", serviceUrl); try { webRequest = WebRequest.Create(serviceUrl) as HttpWebRequest; } catch (UriFormatException ufe) { log.ErrorFormat("Cannot connect to {0} due to {1} ", serviceUrl, ufe.Message); return string.Empty; } if (isPost) { webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; } webRequest.Accept = "application/json"; webRequest.ServicePoint.ConnectionLimit = 10; webRequest.ServicePoint.Expect100Continue = false; //this would prevent waiting infinite time for this HTTP 100 CONTINUE (unuseful) webRequest.CookieContainer = m_cookies; // send out cookie along with a request for the protected page //Add here some custom headers, if needed: //webRequest.Headers.Add("MyCustomHeader", "Header value"); if (isPost && (data != null)) webRequest.ContentLength = data.Length; StreamReader responseReader = null; string responseData = string.Empty; WebResponse webResp = null; try { if (isPost) { log.DebugFormat("Posting request {0}", serviceUrl); // write the form values into the request message StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()); requestWriter.Write(data); requestWriter.Flush(); requestWriter.Close(); requestWriter.Dispose(); } log.DebugFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections); log.DebugFormat("Getting web response for request {0}", serviceUrl); webResp = webRequest.GetResponse(); log.DebugFormat("Getting web response stream for request {0}", serviceUrl); Stream webStream = webResp.GetResponseStream(); log.DebugFormat("Creating reader for request {0}", serviceUrl); responseReader = new StreamReader(webStream); //read the response: log.DebugFormat("Reading response for request {0}", serviceUrl); responseData = responseReader.ReadToEnd(); } catch (WebException wex) { log.ErrorFormat("Cannot connect to {0} due to {1} ", serviceUrl, wex.Message); if ((webRequest != null) && (webRequest.ServicePoint != null)) log.ErrorFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections); return string.Empty; } catch (IOException ioex) { log.ErrorFormat("Cannot read data from to {0} due to {1} ", serviceUrl, ioex.Message); if ((webRequest != null) && (webRequest.ServicePoint != null)) log.ErrorFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections); return string.Empty; } finally { if (responseReader != null) { responseReader.Close(); responseReader.Dispose(); } if (webResp != null) webResp.Close(); webRequest = null; } log.DebugFormat("Response read for request {0}", serviceUrl); return responseData; }

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus