RestClient.cs 4.78 KB
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

public enum HttpVerb
{
    GET,
    POST,
    PUT,
    DELETE
}

namespace HttpUtils
{
    public class RestClient
    {
        public string EndPoint { get; set; }
        public HttpVerb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }

        public RestClient()
        {
            EndPoint = "";
            Method = HttpVerb.GET;
            ContentType = "application/json";
            PostData = "";
        }
        public RestClient(string endpoint)
        {
            EndPoint = endpoint;
            Method = HttpVerb.GET;
            ContentType = "application/json";
            PostData = "";
        }
        public RestClient(string endpoint, HttpVerb method)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "application/json";
            PostData = "";
        }

        public RestClient(string endpoint, HttpVerb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "application/json";
            PostData = postData;
        }

        public static string GetRequestURL(string server, string parameters)
        {
            int timestamp = ConvertToTimestamp(DateTime.Now);
            string hash = CalculateSHA1("/" + parameters + "+" + Cloakroom.Properties.Settings.Default.ApiKey + "+" + Cloakroom.Properties.Settings.Default.ApiUser + "+" + timestamp + "+" + Cloakroom.Properties.Settings.Default.ApiPass);
            string url = server + "/rest/" + parameters + "?appkey=" + Cloakroom.Properties.Settings.Default.ApiKey + "&appuser=" + Cloakroom.Properties.Settings.Default.ApiUser + "&appstamp=" + timestamp + "&appmac=" + hash;
            Console.WriteLine(url);
            return url;
        }

        public static string CalculateSHA1(string text)
        {
            // Convert the input string to a byte array
            byte[] buffer = Encoding.GetEncoding("iso-8859-1").GetBytes(text);

            // In doing your test, you won't want to re-initialize like this every time you test a
            // string.
            SHA1CryptoServiceProvider cryptoTransformSHA1 =
                new SHA1CryptoServiceProvider();

            // The replace won't be necessary for your tests so long as you are consistent in what
            // you compare.    
            string hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "").ToLower();

            return hash;
        }

        private static int ConvertToTimestamp(DateTime value)
        {
            //create Timespan by subtracting the value provided from
            //the Unix Epoch
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

            //return the total seconds (which is a UNIX timestamp)
            return (int)span.TotalSeconds;
        }

        public string MakeRequest()
        {
            return MakeRequest("");
        }



        public string MakeRequest(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(GetRequestURL(EndPoint,parameters));

            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;

            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
            
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                // grab the response
                if (response.ContentLength > 0)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                            using (var reader = new StreamReader(responseStream))
                            {
                                responseValue = reader.ReadToEnd();
                            }
                    }
                }
                return responseValue;
            }
        }

    } // class

}