C#: How do I call an API from a console application?

I have used the following code to call an API and pass in some parameters in the request header.
Have a read here about the Encoding.GetEncoding(1252).

private static string ExecuteAPI(string url, Dictionary<string, string> parameters, string method = "POST", string body = " ", int timeOut = 180000)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = method;

    foreach (var param in parameters)
    {
        request.Headers.Add(param.Key, param.Value);
    }

    if ((method == "POST") || (method == "PUT"))
    {
        if (!string.IsNullOrEmpty(body))
        {
            var requestBody = Encoding.UTF8.GetBytes(body);
            request.ContentLength = requestBody.Length;
            request.ContentType = "application/json";
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(requestBody, 0, requestBody.Length);
            }
        }
        else
        {
            request.ContentLength = 0;
        }
    }
   else
   {
      request.ContentLength = 0;
   }

    request.Timeout = timeOut;
    request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

    string output = string.Empty;
    try
    {
        using (var response = request.GetResponse())
        {
            using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
            {
                output = stream.ReadToEnd();
            }
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            using (var stream = new StreamReader(ex.Response.GetResponseStream()))
            {
                output = stream.ReadToEnd();
            }
        }
        else if (ex.Status == WebExceptionStatus.Timeout)
        {
            output = "Request timeout is expired.";
        }
    }

    return output;
}

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

Error deploying Nintex workflow: An item with the same key has already been added