コード例 #1
0
    public void Signature_Common()
    {
      string httpMethod = "GET";
      string url = "https://localhost/test";
      NameValueCollection param = null;

      var auth = new OAuthAuthorization();
      auth.ConsumerKey= "12345";
      auth.ConsumerSecret = "1234567890";
      auth.TokenSecret = "abc";
      auth.Token = "xyz";
      auth.Nonce = "000000";
      auth.SignatureMethod = "HMAC-SHA1";
      auth.Timestamp = "1111111111";
      auth.Version = "1.0";

      string b = OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth);

      var singn = new OAuthSignature
      (
        auth.SignatureMethod,
        String.Format("{0}&{1}", auth.ConsumerSecret, auth.TokenSecret),
        OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth)
      ).ToString();

      if (singn != "vYE8cEP5ynznQRDqTxx307kc6rY=")
      {
        Assert.Fail();
      }
      else
      {
        Console.WriteLine("OK");
      }

    }
コード例 #2
0
        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();
        }
コード例 #3
0
ファイル: Twitter.cs プロジェクト: DreamerUA/nemiro.oauth.dll
    public ActionResult Twitter(string method)
    {
      try
      {
        if (Session["Twitter:AccessToken"] == null)
        {
          throw new Exception(Test.Resources.Strings.SessionIsDead);
        }

        var token = (OAuthAccessToken)Session["Twitter:AccessToken"];

        string url = "https://api.twitter.com/1.1/followers/ids.json";

        if (method == "user_timeline")
        {
          url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
        }

        var auth = new OAuthAuthorization();
        auth.ConsumerKey = ConfigurationManager.AppSettings["oauth:twitter:id"];
        auth.ConsumerSecret = ConfigurationManager.AppSettings["oauth:twitter:key"];
        auth.TokenSecret = token.TokenSecret;
        auth.SignatureMethod = SignatureMethods.HMACSHA1;
        auth.Nonce = OAuthUtility.GetRandomKey();
        auth.Timestamp = OAuthUtility.GetTimeStamp();
        auth.Token = token.Value;
        auth.Version = "1.0";

        var result = OAuthUtility.ExecuteRequest("GET", url, authorization: auth);

        return Content(result.ToString(), "text/plain");
      }
      catch (Exception ex)
      {
        return Content(ex.ToString(), "text/plain");
      }
    }
コード例 #4
0
    public void Signature_BodyHash()
    {
      string httpMethod = "GET";
      string url = "https://localhost/test";
      NameValueCollection param = null;

      var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

      var auth = new OAuthAuthorization();
      auth.ConsumerKey = "123123123";
      auth.ConsumerSecret = "111111111111";
      auth.SignatureMethod = "HMAC-SHA1";
      auth.Nonce = "10098421";
      auth.Timestamp = "1423300052";
      auth.Version = "1.0";
      auth["oauth_body_hash"] = Convert.ToBase64String(sha1.ComputeHash(new byte[] { }));
      
      string b = OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth);

      var singn = new OAuthSignature
      (
        auth.SignatureMethod,
        String.Format("{0}&{1}", auth.ConsumerSecret, auth.TokenSecret),
        OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth)
      ).ToString();

      if (singn != "0dMQJB8HJSDse2/P4C0icvIbHfU=")
      {
        Assert.Fail();
      }
      else
      {
        Console.WriteLine("OK");
      }

    }
コード例 #5
0
        /// <summary>
        /// Gets base string of the signature for current request (OAuth 1.0).
        /// </summary>
        /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
        public static string GetSignatureBaseString(string httpMethod, Uri url, NameValueCollection parameters, OAuthAuthorization authorization)
        {
            if (String.IsNullOrEmpty(httpMethod))
            {
                throw new ArgumentNullException("httpMethod");
            }
            if (authorization == null)
            {
                throw new ArgumentNullException("authorization");
            }
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var param = new NameValueCollection();

            if (parameters != null)
            {
                param.Add(parameters);
            }

            // append the authorization headers
            foreach (KeyValuePair <string, UniValue> itm in authorization.Value.CollectionItems)
            {
                if (itm.Key.Equals("oauth_signature", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                param.Add(itm.Key, itm.Value.ToString());
            }

            // append the query parameters
            string queryString = url.GetComponents(UriComponents.Query, UriFormat.Unescaped);

            if (!String.IsNullOrEmpty(queryString))
            {
                foreach (string q in queryString.Split('&'))
                {
                    string[] p = q.Split('=');
                    string   key = p.First(), value = (p.Length > 1 ? p.Last() : "");
                    param.Add(key, value);
                }
            }

            // sorting and build base string of the signature
            StringBuilder signBaseString = new StringBuilder();

            foreach (var itm in param.Sort().ToKeyValuePairCollection())
            {
                //if (itm.Key.Equals("oauth_verifier", StringComparison.OrdinalIgnoreCase)) { continue; }
                if (signBaseString.Length > 0)
                {
                    signBaseString.Append(OAuthUtility.UrlEncode("&"));
                }
                signBaseString.Append(OAuthUtility.UrlEncode(String.Format("{0}={1}", itm.Key, OAuthUtility.UrlEncode(itm.Value))));
            }

            signBaseString.Insert(0, String.Format("{0}&{1}&", httpMethod.ToUpper(), OAuthUtility.UrlEncode(url.ToString())));

            return(signBaseString.ToString());
        }
コード例 #6
0
 /// <summary>
 /// Gets base string of the signature for current request (OAuth 1.0).
 /// </summary>
 /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
 public static string GetSignatureBaseString(string httpMethod, string url, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     return(OAuthAuthorization.GetSignatureBaseString(httpMethod, new Uri(url), parameters, authorization));
 }
コード例 #7
0
    /// <summary>
    /// Gets base string of the signature for current request (OAuth 1.0).
    /// </summary>
    /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
    public static string GetSignatureBaseString(string httpMethod, Uri url, NameValueCollection parameters, OAuthAuthorization authorization)
    {
      if (String.IsNullOrEmpty(httpMethod)) { throw new ArgumentNullException("httpMethod"); }
      if (authorization == null) { throw new ArgumentNullException("authorization"); }
      if (url == null) { throw new ArgumentNullException("url"); }

      var param = new NameValueCollection();
      if (parameters != null) { param.Add(parameters); }

      // append the authorization headers
      foreach (KeyValuePair<string, UniValue> itm in authorization.Value.CollectionItems)
      {
        if (itm.Key.Equals("oauth_signature", StringComparison.OrdinalIgnoreCase)) { continue; }
        param.Add(itm.Key, itm.Value.ToString());
      }

      // append the query parameters
      string queryString = url.GetComponents(UriComponents.Query, UriFormat.Unescaped);
      if (!String.IsNullOrEmpty(queryString))
      {
        foreach (string q in queryString.Split('&'))
        {
          string[] p = q.Split('=');
          string key = p.First(), value = (p.Length > 1 ? p.Last() : "");
          param.Add(key, value);
        }
      }

      // sorting and build base string of the signature
      StringBuilder signBaseString = new StringBuilder();
      foreach (var itm in param.Sort().ToKeyValuePairCollection())
      {
        //if (itm.Key.Equals("oauth_verifier", StringComparison.OrdinalIgnoreCase)) { continue; }
        if (signBaseString.Length > 0) { signBaseString.Append(OAuthUtility.UrlEncode("&")); }
        signBaseString.Append(OAuthUtility.UrlEncode(String.Format("{0}={1}", itm.Key, OAuthUtility.UrlEncode(itm.Value))));
      }

      signBaseString.Insert(0, String.Format("{0}&{1}&", httpMethod.ToUpper(), OAuthUtility.UrlEncode(url.ToString())));

      return signBaseString.ToString();
    }
コード例 #8
0
 /// <summary>
 /// Gets base string of the signature for current request (OAuth 1.0).
 /// </summary>
 /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
 public static string GetSignatureBaseString(string httpMethod, string url, NameValueCollection parameters, OAuthAuthorization authorization)
 {
   return OAuthAuthorization.GetSignatureBaseString(httpMethod, new Uri(url), parameters, authorization);
 }
コード例 #9
0
 /// <summary>
 /// Gets signature for the current request.
 /// </summary>
 /// <param name="httpMethod">The HTTP method: <b>GET</b> or <b>POST</b>. Default is <b>POST</b>.</param>
 /// <param name="url">The request URI.</param>
 /// <param name="tokenSecret">The token secret.</param>
 /// <param name="parameters">The query parameters.</param>
 /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
 /// <param name="authorization">The authorization parameters.</param>
 public static OAuthSignature GetSignature(string httpMethod, Uri url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     if (authorization == null)
     {
         throw new ArgumentNullException("authorization");
     }
     return(new OAuthSignature
            (
                authorization["oauth_signature_method"].ToString(),
                String.Format("{0}&{1}", applicationSecret, tokenSecret),
                OAuthUtility.GetSignatureBaseString(httpMethod, url, parameters, authorization)
            ));
 }
コード例 #10
0
 /// <summary>
 /// Gets signature for the current request.
 /// </summary>
 /// <param name="httpMethod">The HTTP method: <b>GET</b> or <b>POST</b>. Default is <b>POST</b>.</param>
 /// <param name="url">The request URI.</param>
 /// <param name="tokenSecret">The token secret.</param>
 /// <param name="parameters">The query parameters.</param>
 /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
 /// <param name="authorization">The authorization parameters.</param>
 public static OAuthSignature GetSignature(string httpMethod, string url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     return(OAuthUtility.GetSignature(httpMethod, new Uri(url), applicationSecret, tokenSecret, parameters, authorization));
 }
コード例 #11
0
 public static OAuthSignature GetSignature(string httpMethod, Uri url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
   if (authorization == null) { throw new ArgumentNullException("authorization"); }
   return new OAuthSignature
   (
     authorization["oauth_signature_method"].ToString(),
     String.Format("{0}&{1}", applicationSecret, tokenSecret),
     OAuthUtility.GetSignatureBaseString(httpMethod, url, parameters, authorization)
   );
 }
コード例 #12
0
 public static OAuthSignature GetSignature(string httpMethod, string url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
   return OAuthUtility.GetSignature(httpMethod, new Uri(url), applicationSecret, tokenSecret, parameters, authorization);
 }
コード例 #13
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);
    }
コード例 #14
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));
        }