Пример #1
0
        internal static string HttpPost(string url, List<string> parameters, CredentialBase credential, HttpRequestMethod httpRequestMethod)
        {
            url += ".json?";

            parameters = parameters.Where(p => !string.IsNullOrEmpty(p)).ToList();

            url = GenerateUrl(url, parameters);

            HttpWebRequest httpRequest;

            if (credential.GetType() == typeof(Credential.OAuth))
            {
                if (!((Credential.OAuth)credential).HasToken)
                    ((Credential.OAuth)credential).Login();

                httpRequest = HttpPostOAuth(url, (Credential.OAuth)credential, httpRequestMethod);
            }
            else
                httpRequest = HttpPostBasic(url, credential, httpRequestMethod);

            try
            {
                using (var response = (HttpWebResponse)httpRequest.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    var result = reader.ReadToEnd();
                    return result;
                }
            }
            catch (WebException ex)
            {
                var result = new StreamReader(ex.Response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                var error = new JavaScriptSerializer().Deserialize<ErrorObj>(result);

                if (!string.IsNullOrEmpty(error.Error))
                    throw new Exception.WebException(error.Error);

                if (!string.IsNullOrEmpty(error.RateLimited))
                    throw new Exception.RateLimitedException(error.RateLimited);

                if (!string.IsNullOrEmpty(error.Unauthorized))
                    throw new Exception.UnauthorizedException(error.Unauthorized);

                throw;
            }
        }
Пример #2
0
        private static HttpWebRequest HttpPostBasic(string url, CredentialBase credential, HttpRequestMethod httpRequestMethod)
        {
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);

            if (credential.GetType() == typeof(Credential.Basic))
            {
                if (!string.IsNullOrEmpty(credential.Username) && !string.IsNullOrEmpty(credential.Password))
                {
                    var authenticationHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", credential.Username, credential.Password)));
                    httpRequest.Headers["Authorization"] = "Basic " + authenticationHeader;
                }
            }

            httpRequest.Method = httpRequestMethod.ToString();

            return httpRequest;
        }