コード例 #1
0
    // [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]

    /// <summary>
    /// Gets the access token from the remote server.
    /// </summary>
    protected override void GetAccessToken()
    {
      // authorization code is required for request
      if (this.GrantType.IsAuthorizationCode && String.IsNullOrEmpty(this.AuthorizationCode))
      {
        throw new ArgumentNullException("AuthorizationCode");
      }
      else if (this.GrantType.IsPassword || this.GrantType.IsClientCredentials)
      {
        if (String.IsNullOrEmpty(this.Username))
        {
          throw new ArgumentNullException("username");
        }
        if (String.IsNullOrEmpty(this.Password))
        {
          throw new ArgumentNullException("password");
        }
      }

      // set default access token value
      this.AccessToken = Nemiro.OAuth.AccessToken.Empty;
      
      // set request data
      HttpAuthorization auth = null;
      NameValueCollection parameters = new NameValueCollection();

      if (this.GrantType.IsAuthorizationCode)
      {
        // http://tools.ietf.org/html/rfc6749#section-4.1.3
        parameters.Add("code", this.AuthorizationCode);
      }
      else if (this.GrantType.IsPassword)
      {
        // http://tools.ietf.org/html/rfc6749#section-4.3.2
        parameters.Add("username", this.Username);
        parameters.Add("password", this.Password);
      }
      else if (this.GrantType.IsClientCredentials)
      {
        // http://tools.ietf.org/html/rfc6749#section-4.4.2
        auth = new HttpAuthorization(AuthorizationType.Basic, OAuthUtility.ToBase64String("{0}:{1}", this.Username, this.Password));
      }
      else
      {
        throw new NotSupportedException(String.Format("GrantType '{0}' is not supported. Please write the code ;)", this.GrantType));
      }
      
      parameters.Add("client_id", this.ApplicationId);
      parameters.Add("client_secret", this.ApplicationSecret);
      parameters.Add("grant_type", this.GrantType);


      if (!String.IsNullOrEmpty(this.ReturnUrl))
      {
        parameters.Add("redirect_uri", this.ReturnUrl);
      }

      var result = OAuthUtility.Post
      (
        this.AccessTokenUrl,
        parameters,
        auth
      );

      if (result.ContainsKey("error"))
      {
        this.AccessToken = new AccessToken(new ErrorResult(result));
      }
      else
      {
        this.AccessToken = new OAuth2AccessToken(result);
      }
    }
コード例 #2
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();
 }
コード例 #3
0
        // [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]

        /// <summary>
        /// Gets the access token from the remote server.
        /// </summary>
        protected override void GetAccessToken()
        {
            // authorization code is required for request
            if (this.GrantType.IsAuthorizationCode && String.IsNullOrEmpty(this.AuthorizationCode))
            {
                throw new ArgumentNullException("AuthorizationCode");
            }
            else if (this.GrantType.IsPassword || this.GrantType.IsClientCredentials)
            {
                if (String.IsNullOrEmpty(this.Username))
                {
                    throw new ArgumentNullException("username");
                }
                if (String.IsNullOrEmpty(this.Password))
                {
                    throw new ArgumentNullException("password");
                }
            }

            // set default access token value
            this.AccessToken = Nemiro.OAuth.AccessToken.Empty;

            // set request data
            HttpAuthorization   auth       = null;
            NameValueCollection parameters = new NameValueCollection();

            if (this.GrantType.IsAuthorizationCode)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.1.3
                parameters.Add("code", this.AuthorizationCode);
            }
            else if (this.GrantType.IsPassword)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.3.2
                parameters.Add("username", this.Username);
                parameters.Add("password", this.Password);
            }
            else if (this.GrantType.IsClientCredentials)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.4.2
                auth = new HttpAuthorization(AuthorizationType.Basic, OAuthUtility.ToBase64String("{0}:{1}", this.Username, this.Password));
            }
            else
            {
                throw new NotSupportedException(String.Format("GrantType '{0}' is not supported. Please write the code ;)", this.GrantType));
            }

            parameters.Add("client_id", this.ApplicationId);
            parameters.Add("client_secret", this.ApplicationSecret);
            parameters.Add("grant_type", this.GrantType);


            if (!String.IsNullOrEmpty(this.ReturnUrl))
            {
                parameters.Add("redirect_uri", this.ReturnUrl);
            }

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters,
                auth
                         );

            if (result.ContainsKey("error"))
            {
                this.AccessToken = new AccessToken(new ErrorResult(result));
            }
            else
            {
                this.AccessToken = new OAuth2AccessToken(result);
            }
        }
コード例 #4
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);
 }
コード例 #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 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);
 }
コード例 #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 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();
        }
コード例 #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);
 }
コード例 #10
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);
 }
コード例 #11
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);
 }
コード例 #12
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));
        }
コード例 #13
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));
 }
コード例 #14
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));
 }