internal override void Build(string httpMethod, string url, string contentType, HttpParameterCollection parameters)
        {
            NameValueCollection param = null;

            if (parameters != null)
            {
                if (!String.IsNullOrEmpty(contentType) && contentType.ToLower().Contains("multipart/form-data"))
                {
                    param = ((HttpParameterCollection)parameters.Where(itm => itm.ParameterType == HttpParameterType.Url).ToArray()).ToNameValueCollection();
                }
                else
                {
                    param = parameters.ToNameValueCollection();
                }
            }
            this.Signature = new OAuthSignature
                             (
                this.SignatureMethod.ToString(),
                String.Format("{0}&{1}", this.ConsumerSecret, this.TokenSecret),
                OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, this)
                             ).ToString();
        }
 public void SetSignature(string httpMethod, string url, string applicationSecret, string tokenSecret, HttpParameterCollection parameters)
 {
     this.SetSignature(httpMethod, url, applicationSecret, tokenSecret, parameters);
 }
示例#3
0
        /// <summary>
        /// Performs an async 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 request.</param>
        /// <param name="contentType">The value of the <b>Content-Type</b> HTTP header.</param>
        /// <param name="callback">A delegate that, if provided, is called when an async web request is completed.</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 void ExecuteRequestAsync(string method = "POST", string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null)
        {
            var t = new Thread
                        (() =>
            {
                RequestResult result = null;
                try
                {
                    result = OAuthUtility.ExecuteRequest(method, endpoint, parameters, authorization, headers, contentType, accessToken);
                }
                catch (RequestException ex)
                {
                    result = ex.RequestResult;
                }
                if (callback != null)
                {
                    callback(result);
                }
            }
                        );

            t.IsBackground = true;
            t.Start();
        }
示例#4
0
 /// <summary>
 /// Invoked before sending a web request.
 /// </summary>
 /// <param name="httpMethod">HTTP Method of the request: <b>POST</b>, <b>PUT</b>, <b>GET</b> or <b>DELETE</b>.</param>
 /// <param name="url">URL of the web request.</param>
 /// <param name="contentType">The value of the <b>Content-Type</b> HTTP header.</param>
 /// <param name="parameters">>Parameters of the web request.</param>
 internal virtual void Build(string httpMethod, string url, string contentType, HttpParameterCollection parameters)
 {
 }
示例#5
0
 /// <summary>
 /// Performs an async request using a <b>DELETE</b> method.
 /// </summary>
 /// <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 request.</param>
 /// <param name="callback">A delegate that, if provided, is called when an async request is completed.</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 void DeleteAsync(string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null)
 {
     OAuthUtility.ExecuteRequestAsync("DELETE", endpoint, parameters, authorization, headers, null, accessToken, callback);
 }
示例#6
0
 /// <summary>
 /// Performs an async request using a <b>PUT</b> method.
 /// </summary>
 /// <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 request.</param>
 /// <param name="contentType">The value of the <b>Content-Type</b> HTTP header.</param>
 /// <param name="callback">A delegate that, if provided, is called when an async request is completed.</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 void PutAsync(string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null)
 {
     OAuthUtility.ExecuteRequestAsync("PUT", endpoint, parameters, authorization, headers, contentType, accessToken, callback);
 }
示例#7
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));
        }
示例#8
0
 /// <summary>
 /// Performs a request using a <b>DELETE</b> method.
 /// </summary>
 /// <param name="endpoint">URL to which will be sent to the request.</param>
 /// <param name="parameters">Parameters to be passed to the request.</param>
 /// <param name="authorization">Authorization header value.</param>
 /// <param name="headers">HTTP headers for the request.</param>
 /// <param name="accessToken">Access token to be used in the request.</param>
 /// <returns>Returns an instance of the <see cref="RequestResult"/> class, which contains the result of the request.</returns>
 /// <remarks>
 /// <para>Can not be used simultaneously <paramref name="accessToken"/> and <paramref name="authorization"/>. Use only one of these parameters.</para>
 /// </remarks>
 /// <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 Delete(string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, AccessToken accessToken = null)
 {
     return(OAuthUtility.ExecuteRequest("DELETE", endpoint, parameters, authorization, headers, null, accessToken));
 }
示例#9
0
 /// <summary>
 /// Performs a request using a <b>PUT</b> method.
 /// </summary>
 /// <param name="endpoint">URL to which will be sent to the request.</param>
 /// <param name="parameters">Parameters to be passed to the request.</param>
 /// <param name="authorization">Authorization header value.</param>
 /// <param name="headers">HTTP headers for the 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 Put(string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null)
 {
     return(OAuthUtility.ExecuteRequest("PUT", endpoint, parameters, authorization, headers, contentType, accessToken));
 }