PageRenderTime 53ms CodeModel.GetById 20ms app.highlight 8ms RepoModel.GetById 22ms app.codeStats 1ms

/src/Server/DeviceHive.Test/JsonClient.cs

https://github.com/oryol/devicehive-.net
C# | 135 lines | 118 code | 14 blank | 3 comment | 7 complexity | 9df93fdbc6711121cab0a9e140e06325 MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Net;
  5using System.IO;
  6using System.Text;
  7using Newtonsoft.Json;
  8using Newtonsoft.Json.Linq;
  9
 10namespace DeviceHive.Test
 11{
 12    public class JsonClient
 13    {
 14        private string _baseUrl;
 15
 16        public JsonClient(string baseUrl)
 17        {
 18            _baseUrl = baseUrl;
 19        }
 20
 21        public JsonResponse Get(string url, Authorization auth = null)
 22        {
 23            return Run("GET", url, auth: auth);
 24        }
 25
 26        public JsonResponse Post(string url, object request, Authorization auth = null)
 27        {
 28            return Run("POST", url, jsonRequest: JObject.FromObject(request), auth: auth);
 29        }
 30
 31        public JsonResponse Put(string url, object request, Authorization auth = null)
 32        {
 33            return Run("PUT", url, jsonRequest: JObject.FromObject(request), auth: auth);
 34        }
 35
 36        public JsonResponse Delete(string url, Authorization auth = null)
 37        {
 38            return Run("DELETE", url, auth: auth);
 39        }
 40
 41        public JsonResponse Run(string method, string url, JObject jsonRequest = null, Authorization auth = null)
 42        {
 43            if (string.IsNullOrEmpty(method))
 44                throw new ArgumentException("Method is null or empty!", "method");
 45            if (string.IsNullOrEmpty(url))
 46                throw new ArgumentException("URL is null or empty!", "url");
 47
 48            // prepare request
 49            var request = (HttpWebRequest)HttpWebRequest.Create(_baseUrl + url);
 50            request.Method = method;
 51            request.Accept = "application/json";
 52            if (auth != null)
 53            {
 54                switch (auth.Type)
 55                {
 56                    case "User":
 57                        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(
 58                            Encoding.UTF8.GetBytes(string.Format("{0}:{1}", auth.Login, auth.Password)));
 59                        break;
 60                    case "Device":
 61                        request.Headers["Auth-DeviceID"] = auth.Login;
 62                        request.Headers["Auth-DeviceKey"] = auth.Password;
 63                        break;
 64                }
 65            }
 66            if (jsonRequest != null)
 67            {
 68                request.ContentType = "application/json";
 69                using (var stream = request.GetRequestStream())
 70                {
 71                    using (var writer = new StreamWriter(stream))
 72                    {
 73                        writer.Write(jsonRequest.ToString());
 74                    }
 75                }
 76            }
 77
 78            // perform a call
 79            HttpWebResponse response;
 80            try
 81            {
 82                response = (HttpWebResponse)request.GetResponse();
 83            }
 84            catch (WebException ex)
 85            {
 86                response = (HttpWebResponse)ex.Response;
 87            }
 88
 89            // parse response
 90            using (var stream = response.GetResponseStream())
 91            {
 92                using (var reader = new StreamReader(stream))
 93                {
 94                    var responseString = reader.ReadToEnd();
 95                    try
 96                    {
 97                        var json = string.IsNullOrEmpty(responseString) ? null : JToken.Parse(responseString);
 98                        return new JsonResponse((int)response.StatusCode, json);
 99                    }
100                    catch (JsonReaderException ex)
101                    {
102                        throw new WebException(string.Format("Error while parsing server response! " +
103                            "Status: {0}, Response: {1}", (int)response.StatusCode, responseString), ex);
104                    }
105                }
106            }
107        }
108    }
109
110    public class Authorization
111    {
112        public string Type { get; private set; }
113        public string Login { get; private set; }
114        public string Password { get; private set; }
115
116        public Authorization(string type, string login, string password)
117        {
118            Type = type;
119            Login = login;
120            Password = password;
121        }
122    }
123
124    public class JsonResponse
125    {
126        public int Status { get; private set; }
127        public JToken Json { get; private set; }
128
129        public JsonResponse(int status, JToken json)
130        {
131            Status = status;
132            Json = json;
133        }
134    }
135}