There are several ways to perform HTTP GET, POST.. requests in C#. The following example is using the legacy HttpRequest Class provided by .NetFramework without adding one more additional dependency (Nuget Packages) for something that works really well in .NET implementation and is usually unnecessary for small hobby projects but also not a good practice in professional projects.
WebRequest and more specifically the HttpWebRequest class is a good starting point for our purpose. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it.
Please feel free to use the following code snippet as a reference to your actual implementation.
public enum HTTPRequestStatus
{
OK = 0x00,
Timeout = 0x01,
Error = 0xff
}
////////////////////////////////////////////////////////////////////////
public class HTTPResult
{
public HTTPRequestStatus Status;
public object Value;
}
////////////////////////////////////////////////////////////////////////
public static HTTPResult HTTPRequest(string url, string method,
string contentType = "application/json",
string[] headers = null, string body = null,
int timeout = 10000)
{
HttpWebRequest httpWebRequest;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method;
httpWebRequest.ContentType = contentType;
if (headers != null)
for (int i = 0; i < headers.Length; i++)
httpWebRequest.Headers.Add(headers[i]);
httpWebRequest.Timeout = timeout;
if (!string.IsNullOrWhiteSpace(body))
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
return new HTTPResult()
{ Status = HTTPRequestStatus.OK, Value = streamReader.ReadToEnd() };
}
}
catch (Exception ex)
{
try
{
if (((WebException)ex).Status == WebExceptionStatus.Timeout)
return new HTTPResult() { Status = HTTPRequestStatus.Timeout, Value = null };
}
catch (Exception)
{ }
return new HTTPResult() { Status = HTTPRequestStatus.Error, Value = null };
}
}
////////////////////////////////////////////////////////////////////////
// Usage
////////////////////////////////////////////////////////////////////////
var o = HTTPRequest("https://devcoons.com","GET");
....
var o = HTTPRequest("https://devcoons.com","GET","application/json");
....
var o = HTTPRequest("https://devcoons.com","GET","application/json",
new string[]{"Authorization: Bearer xxxx"});