Help & Support
Follow

LeanKit API (v1): Example Code for making an HttpRequest in C#

Depending on your language and platform, there are any number of ways to make an http request, specify the username and password for basic authentication, and append data to the request body for an HTTP Post. (some of them would be much easier in other languages than the example you're about to see). This example code is from our unit tests of our API, and shows how to do some of these basic functions in the c# language.

public string DoWebRequest(string address, string method)
{
    return DoWebRequest(address, method, string.Empty);
}

public string DoWebRequest(string address, string method, string body)
{
    var request = (HttpWebRequest)WebRequest.Create("https://myaccount.leankit.com/" + address);
    request.Method = method;
    request.Credentials = new NetworkCredential("demo@leankit.com", "demopassword");
    request.PreAuthenticate = true;

    if (method == "POST")
    {
        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;
        }
    }

    request.Timeout = 15000;
    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.";
        }
    }
    Console.WriteLine(output);

    return output;
}

 

 

 

 

 

 

Doc ID: 1191979653

Have more questions? Submit a request