public async Task QueryByInvalidLocationTest()
        {
            //Act
            var responseMessage = await RestApiWrapper.Get <IMetaWeatherApi>(s => s.QueryByLocation("invalid"));

            //Assert
            Assert.False(responseMessage.IsSuccessStatusCode);
        }
        //[ExpectedException(typeof(ConfigFileReadError))]
        public void GetAccountIdTest()
        {
            IRestApiWrapper wrapper = new RestApiWrapper(new System.Net.Http.HttpClient(), new JsonConfiguration());

            _username = "******";
            string response = wrapper.GetAccountId(_username, _password);

            Assert.AreEqual("4823252", response);
        }
Esempio n. 3
0
 public GeeklistService(string consumerKey, string consumerSecret, string callback = "oob")
 {
     api = new RestApiWrapper(consumerKey, consumerSecret, callback);
 }
Esempio n. 4
0
    /// <summary>
    /// Make a single request.
    /// </summary>
    /// <param name="url">URL to request.</param>
    /// <param name="method">HTTP method to use.</param>
    /// <param name="body">Body to transmit.</param>
    /// <param name="headers">Headers to transmit.</param>
    /// <returns>Wrapper for request attempt.</returns>
    public RestApiWrapper Request(string url, string method, object body = null,
                                  Dictionary <string, string> headers    = null)
    {
        var wrapper = new RestApiWrapper {
            Start   = DateTime.Now,
            Request = new RestApiWrapper.RestApiWrapperRequest {
                Url               = this.BaseUrl + url,
                Method            = method.ToUpper(),
                Headers           = this.GlobalHeaders,
                BasicAuthUsername = this.BasicAuthUsername,
                BasicAuthPassword = this.BasicAuthPassword,
                ClientCertificate = this.ClientCertificate
            }
        };

        // Add given headers.
        if (headers != null)
        {
            if (wrapper.Request.Headers == null)
            {
                wrapper.Request.Headers = new Dictionary <string, string>();
            }

            foreach (var header in headers)
            {
                wrapper.Request.Headers.Add(header.Key, header.Value);
            }
        }

        // Prepare body.
        if (body != null)
        {
            if (body is string)
            {
                wrapper.Request.Body = body.ToString();
            }
            else
            {
                wrapper.Request.Body = JsonConvert.SerializeObject(body);
            }
        }

        try {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            Stream stream;
            var    req = WebRequest.Create(wrapper.Request.Url) as HttpWebRequest;

            if (req == null)
            {
                throw new Exception("Unable to create a HttpWebRequest.");
            }

            req.Method    = wrapper.Request.Method;
            req.UserAgent = "RestApiWrapper";

            // Add basic auth.
            if (!string.IsNullOrWhiteSpace(wrapper.Request.BasicAuthUsername) &&
                !string.IsNullOrWhiteSpace(wrapper.Request.BasicAuthPassword))
            {
                var b64e = Convert.ToBase64String(
                    Encoding.UTF8.GetBytes(
                        string.Format("{0}:{1}",
                                      wrapper.Request.BasicAuthUsername,
                                      wrapper.Request.BasicAuthPassword)));

                req.Headers.Add(
                    "Authorization",
                    string.Format("Basic {0}",
                                  b64e));
            }

            // Add client certificate.
            if (wrapper.Request.ClientCertificate != null)
            {
                req.ClientCertificates.Add(wrapper.Request.ClientCertificate);
            }

            // Add body.
            if (!string.IsNullOrWhiteSpace(wrapper.Request.Body))
            {
                var bytes = Encoding.UTF8.GetBytes(wrapper.Request.Body);

                req.ContentLength = bytes.Length;
                req.ContentType   = "application/json; charset=utf-8";

                stream = req.GetRequestStream();

                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }

            // Store request headers.
            if (wrapper.Request.Headers == null)
            {
                wrapper.Request.Headers = new Dictionary <string, string>();
            }

            foreach (var key in req.Headers.AllKeys)
            {
                if (wrapper.Request.Headers.ContainsKey(key))
                {
                    continue;
                }

                wrapper.Request.Headers.Add(key, req.Headers[key]);
            }

            // Get response.
            var res = req.GetResponse() as HttpWebResponse;

            if (res == null)
            {
                throw new Exception("Unable to get HttpWebResponse.");
            }

            if (wrapper.Response == null)
            {
                wrapper.Response = new RestApiWrapper.RestApiWrapperResponse();
            }

            wrapper.Response.StatusCode        = res.StatusCode;
            wrapper.Response.StatusDescription = res.StatusDescription;

            // Get response headers.
            if (res.Headers.AllKeys.Any())
            {
                if (wrapper.Response.Headers == null)
                {
                    wrapper.Response.Headers = new Dictionary <string, string>();
                }

                foreach (var key in res.Headers.AllKeys)
                {
                    wrapper.Response.Headers.Add(key, res.Headers[key]);
                }
            }

            // Get response body.
            stream = res.GetResponseStream();

            if (stream != null)
            {
                var reader = new StreamReader(stream, Encoding.UTF8);
                wrapper.Response.Body = reader.ReadToEnd();
            }
        }
        catch (WebException ex) {
            wrapper.Exception = ex;

            var res = ex.Response as HttpWebResponse;

            if (res != null)
            {
                if (wrapper.Response == null)
                {
                    wrapper.Response = new RestApiWrapper.RestApiWrapperResponse();
                }

                wrapper.Response.StatusCode        = res.StatusCode;
                wrapper.Response.StatusDescription = res.StatusDescription;

                var stream = res.GetResponseStream();

                if (stream != null)
                {
                    var reader = new StreamReader(stream, Encoding.UTF8);
                    wrapper.Response.Body = reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex) {
            wrapper.Exception = ex;
        }

        wrapper.End      = DateTime.Now;
        wrapper.Duration = wrapper.End - wrapper.Start;

        return(wrapper);
    }