/// <summary>
        /// Performs a web request.
        /// </summary>
        /// <param name="method">HTTP Method: <b>POST</b> (default) or <b>GET</b>.</param>
        /// <param name="endpoint">URL to which will be sent to web request.</param>
        /// <param name="parameters">Parameters to be passed to web request.</param>
        /// <param name="authorization">Authorization header value.</param>
        /// <param name="headers">HTTP headers for web request.</param>
        /// <returns>Returns an instance of the <see cref="RequestResult"/> class, which contains the result of the web request.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="RequestException"></exception>
        public static RequestResult ExecuteRequest(string method = "POST", string endpoint = null, NameValueCollection parameters = null, string authorization = null, NameValueCollection headers = null)
        {
            if (String.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("endpoint");
            }
            if (String.IsNullOrEmpty(method))
            {
                method = "POST";
            }

            // set protocols
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
            // ignore errors
            ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            // --

            // set parameters to the URL if the request is executed using the GET method
            if (method.Equals("GET", StringComparison.OrdinalIgnoreCase) && parameters != null && parameters.Count > 0)
            {
                endpoint += (endpoint.Contains("?") ? "&" : "?");
                endpoint += parameters.ToParametersString("&");
            }

            // create request
            var req = (HttpWebRequest)HttpWebRequest.Create(endpoint);

            // http method
            req.Method = method.ToUpper();

            // req.ProtocolVersion = HttpVersion.Version10;

            // user-agent (required for some providers)
            req.UserAgent = "Nemiro.OAuth";

            // json format acceptable for the response
            req.Accept = "application/json";

            // set parameters to the body if the request is executed using the POST method
            if (method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                req.ContentType = "application/x-www-form-urlencoded";
                if (parameters != null && parameters.Count > 0)
                {
                    byte[] b = System.Text.Encoding.ASCII.GetBytes(parameters.ToParametersString("&"));
                    // for .NET Framework 2.0/3.0/3.5
                    if (Environment.Version.Major < 4)
                    {
                        req.ContentLength = b.Length;
                    }
                    // --
                    req.GetRequestStream().Write(b, 0, b.Length);
                }
                else
                {
                    // for some servers
                    req.ContentLength = 0;
                }
            }

            // set authorization header
            if (!String.IsNullOrEmpty(authorization))
            {
                if (headers == null)
                {
                    headers = new NameValueCollection();
                }
                if (String.IsNullOrEmpty(headers["Authorization"]))
                {
                    headers.Add("Authorization", authorization);
                }
                else
                {
                    headers["Authorization"] = authorization;
                }
            }

            // headers
            if (headers != null)
            {
                req.Headers.Add(headers);
            }

            Exception exception = null;
            string    result = "", contentType = "";

            try
            {
                // executes the request
                using (var resp = (HttpWebResponse)req.GetResponse())
                {
                    contentType = resp.ContentType;
                    result      = OAuthUtility.ReadResponseStream(resp);
                }
            }
            catch (WebException ex)
            {     // web exception,
                if (ex.Response != null)
                { // reading contents of the response
                    using (var resp = (HttpWebResponse)ex.Response)
                    {
                        contentType = resp.ContentType;
                        result      = OAuthUtility.ReadResponseStream(resp);
                    }
                }
                else
                { // no response, get error message
                    result = ex.Message;
                }
                exception = ex;
            }
            catch (Exception ex)
            { // other exception
                result    = ex.Message;
                exception = ex;
            }

            // exception
            if (exception != null)
            {
                throw new RequestException(contentType, result, exception);
            }

            // result
            return(new RequestResult(contentType, result));
        }
Example #2
0
        /// <summary>
        /// Performs a request.
        /// </summary>
        /// <param name="method">HTTP Method: <b>POST</b> (default), <b>PUT</b>, <b>GET</b> or <b>DELETE</b>.</param>
        /// <param name="endpoint">URL to which will be sent to request.</param>
        /// <param name="parameters">Parameters to be passed to request.</param>
        /// <param name="authorization">Authorization header value.</param>
        /// <param name="headers">HTTP headers for web request.</param>
        /// <param name="contentType">The value of the <b>Content-Type</b> HTTP header.</param>
        /// <param name="accessToken">Access token to be used in the request.</param>
        /// <remarks>
        /// <para>Can not be used simultaneously <paramref name="accessToken"/> and <paramref name="authorization"/>. Use only one of these parameters.</para>
        /// </remarks>
        /// <returns>Returns an instance of the <see cref="RequestResult"/> class, which contains the result of the request.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="RequestException"></exception>
        /// <exception cref="ArgumentException">
        /// <para>The exception occurs when the query parameters are specified at the same time <paramref name="authorization"/> and <paramref name="accessToken"/>.</para>
        /// </exception>
        public static RequestResult ExecuteRequest(string method = "POST", string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null)
        {
            // checking
            if (String.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("endpoint");
            }
            if (!AccessToken.IsNullOrEmpty(accessToken) && authorization != null)
            {
                throw new ArgumentException("The request can not contain both authorization headers and access token.");
            }

            // set default values
            if (!String.IsNullOrEmpty(method))
            {
                method = method.ToUpper();
            }
            string[] post = { "POST", "PUT" };
            if (String.IsNullOrEmpty(method) || (parameters != null && (parameters.HasFiles || parameters.IsRequestBody) && Array.IndexOf(post, method) == -1))
            {
                method = "POST";
            }
            bool isPost = Array.IndexOf(post, method) != -1;

            // set protocols
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            // ignore errors
            ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            // --

            // access token
            if (!AccessToken.IsNullOrEmpty(accessToken))
            {
                if (accessToken.GetType() == typeof(OAuth2AccessToken) || accessToken.GetType().IsSubclassOf(typeof(OAuth2AccessToken)))
                {
                    // is oauth 2.0
                    var token = (OAuth2AccessToken)accessToken;
                    if (!String.IsNullOrEmpty(token.TokenType) && (token.TokenType.Equals(AccessTokenType.Bearer, StringComparison.OrdinalIgnoreCase))) //  || token.TokenType.Equals(AccessTokenType.OAuth, StringComparison.OrdinalIgnoreCase)
                    {
                        // bearer
                        authorization = new HttpAuthorization(AuthorizationType.Bearer, accessToken.Value);
                    }
                    else
                    {
                        // other
                        if (parameters == null)
                        {
                            parameters = new HttpParameterCollection();
                        }
                        parameters.AddUrlParameter("access_token", accessToken.Value);
                    }
                }
                else if (accessToken.GetType() == typeof(OAuthAccessToken) || accessToken.GetType().IsSubclassOf(typeof(OAuthAccessToken)))
                {
                    // is oauth 1.0
                    authorization = new OAuthAuthorization(accessToken);
                }
                else
                {
                    // I do not know that. But it's definitely need to consider.
                    if (parameters == null)
                    {
                        parameters = new HttpParameterCollection();
                    }
                    parameters.AddUrlParameter("access_token", accessToken.Value);
                }
            }
            // --

            string requestUrl = endpoint; // need source endpoint for signature

            if (!isPost && parameters != null && parameters.Count > 0)
            {
                // set parameters to the URL if the request is executed using the GET method
                requestUrl += (requestUrl.Contains("?") ? "&" : "?");
                requestUrl += parameters.ToStringParameters();
            }
            else if (isPost && parameters != null && parameters.Count > 0)
            {
                // is POST or PUT method
                if (parameters.IsRequestBody)
                {
                    // all parameters to url
                    HttpParameterCollection p = parameters.Where(itm => itm.ParameterType != HttpParameterType.RequestBody).ToArray();
                    if (p.Count > 0)
                    {
                        requestUrl += (requestUrl.Contains("?") ? "&" : "?");
                        requestUrl += p.ToStringParameters();
                    }
                }
                else
                {
                    // url parameters to endpoint
                    HttpParameterCollection p = parameters.Where(itm => itm.ParameterType == HttpParameterType.Url).ToArray();
                    if (p.Count > 0)
                    {
                        requestUrl += (requestUrl.Contains("?") ? "&" : "?");
                        requestUrl += p.ToStringParameters();
                    }
                }
            }

            // create request
            var req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            // http method
            req.Method = method;

            // req.ProtocolVersion = HttpVersion.Version10;

            // user-agent (required for some providers)
            req.UserAgent = "Nemiro.OAuth";

            // json format acceptable for the response
            req.Accept = "application/json";

            // set parameters to the body if the request is executed using the POST method
            if (isPost)
            {
                if (parameters != null && parameters.Count > 0)
                {
                    req.ContentType = contentType;
                    parameters.WriteToRequestStream(req);
                }
                else
                {
                    // for some servers
                    req.ContentLength = 0;
                }
            }

            // set authorization header
            if (authorization != null)
            {
                // build authorization
                authorization.Build(method, endpoint, req.ContentType, parameters);
                // add authorization to headers
                if (headers == null)
                {
                    headers = new NameValueCollection();
                }
                if (String.IsNullOrEmpty(headers["Authorization"]))
                {
                    headers.Add("Authorization", authorization.ToString());
                }
                else
                {
                    headers["Authorization"] = authorization.ToString();
                }
            }

            // headers
            if (headers != null)
            {
                req.Headers.Add(headers);
            }

            WebHeaderCollection rh        = null;
            Exception           exception = null;
            string ct     = "";
            int    status = 0;

            byte[] result;

            try
            {
                // executes the request
                using (var resp = (HttpWebResponse)req.GetResponse())
                {
                    ct     = resp.ContentType;
                    rh     = resp.Headers;
                    status = (int)resp.StatusCode;
                    result = OAuthUtility.ReadResponseStream(resp);
                }
            }
            catch (WebException ex)
            {     // web exception,
                if (ex.Response != null)
                { // reading contents of the response
                    using (var resp = (HttpWebResponse)ex.Response)
                    {
                        ct     = resp.ContentType;
                        rh     = resp.Headers;
                        status = (int)resp.StatusCode;
                        result = OAuthUtility.ReadResponseStream(resp);
                    }
                }
                else
                { // no response, get error message
                    result = Encoding.UTF8.GetBytes(ex.Message);
                }
                exception = ex;
            }
            catch (Exception ex)
            { // other exception
                result    = Encoding.UTF8.GetBytes(ex.Message);
                exception = ex;
            }

            // exception
            if (exception != null)
            {
                throw new RequestException(ct, result, exception, rh, status);
            }

            // result
            return(new RequestResult(ct, result, rh, status));
        }