Esempio n. 1
0
        public virtual OAuthAccessToken GetAccessToken(OAuthRequestToken requestToken, string verifier)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token          = requestToken.Token,
                TokenSecret    = requestToken.TokenSecret,
                Verifier       = verifier
            };

            var request  = _accessTokenQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query       = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
            {
                Token       = query["oauth_token"] ?? "?",
                TokenSecret = query["oauth_token_secret"] ?? "?",
                UserId      = Convert.ToInt32(query["user_id"] ?? "0"),
                ScreenName  = query["screen_name"] ?? "?"
            };

            return(accessToken);
        }
Esempio n. 2
0
        public virtual OAuthRequestToken GetRequestToken(string callback)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret
            };

            var request = _requestTokenQuery.Invoke(args);

            if (!callback.IsNullOrBlank())
            {
                request.AddParameter("oauth_callback", callback);
            }

            var response = _oauth.Request(request);

            SetResponse(response);

            var query = HttpUtility.ParseQueryString(response.Content);
            var oauth = new OAuthRequestToken
            {
                Token                  = query["oauth_token"] ?? "?",
                TokenSecret            = query["oauth_token_secret"] ?? "?",
                OAuthCallbackConfirmed = Convert.ToBoolean(query["oauth_callback_confirmed"] ?? "false")
            };

            return(oauth);
        }
Esempio n. 3
0
        public virtual OAuthAccessToken GetAccessTokenWithXAuth(string username, string password)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Username       = username,
                Password       = password
            };

            var request  = _xAuthQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query       = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
            {
                Token       = query["oauth_token"] ?? "?",
                TokenSecret = query["oauth_token_secret"] ?? "?",
                UserId      = Convert.ToInt32(query["user_id"] ?? "0"),
                ScreenName  = query["screen_name"] ?? "?"
            };

            return(accessToken);
        }
        private NameValueCollection ParseQueryParameters(Stream stream)
        {
            var rawPostData = new StringBuilder();

            char[] buffer = new char[StreamReaderBufferSize];
            using (StreamReader streamReader = new StreamReader(stream)) {
                int readLength = 0;
                while ((readLength = streamReader.ReadBlock(buffer, 0, StreamReaderBufferSize)) > 0)
                {
                    if (readLength < StreamReaderBufferSize)
                    {
                        char[] bufferLast = buffer.Take(readLength).ToArray();
                        rawPostData.Append(bufferLast);
                        bufferLast = null;
                    }
                    else
                    {
                        rawPostData.Append(buffer);
                    }
                }
            }
            buffer = null;
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(rawPostData.ToString(), Encoding.UTF8);

            rawPostData.Clear();
            return(queryParameters);
        }
Esempio n. 5
0
        public static Uri AddQueryParamsToUri(Uri uri, IEnumerable <KeyValuePair <string, string> > newQuery)
        {
            var query = HttpUtility.ParseQueryString(uri.Query);

            foreach (var entry in newQuery)
            {
                query[entry.Key] = entry.Value;
            }

            var builder = new UriBuilder(uri);

            builder.Query = query.ToString();

            return(builder.Uri);
        }
        /// <summary>
        /// ############## ##### ######### ###### <see cref="LeadSourceHelper"/>.
        /// </summary>
        /// <param name="userConnection">######### ################# ###########.</param>
        /// <param name="bpmHref">URL ########.</param>
        /// <param name="bpmRef">URL #########.</param>
        public LeadSourceHelper(UserConnection userConnection, string bpmHref, string bpmRef)
        {
            this.userConnection = userConnection;
            this.bpmHref        = bpmHref;
            this.bpmRef         = bpmRef;
            Uri uri;

            if (Uri.TryCreate(this.bpmHref, UriKind.Absolute, out uri))
            {
                bpmHrefParameters = HttpUtility.ParseQueryString(uri.Query);
            }
            else
            {
                bpmHrefParameters = HttpUtility.ParseQueryString(string.Empty);
            }
        }
Esempio n. 7
0
        Uri QualifyUri(string path, QueryString queryString = null)
        {
            if (queryString != null && queryString.Count > 0)
            {
                Uri uri = linkResolver.Resolve(path);

                NameValueCollection currentQueryStrings = HttpUtility.ParseQueryString(uri.Query);
                foreach (var pair in queryString)
                {
                    currentQueryStrings.Set(pair.Key, pair.Value.ToString());
                }
                path = string.Concat(uri.AbsolutePath, "?", currentQueryStrings);
            }

            return(linkResolver.Resolve(path));
        }
Esempio n. 8
0
        public bool GetAccessToken()
        {
            BuildRequestUrl();
            string      content;
            WebResponse response;

            try
            {
                var request = WebRequest.Create(requestUrl);
                response = request.GetResponse();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                response = ex.Response;
                if (response != null)
                {
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        var error = sr.ReadToEnd();
                        Syslog.Write("oauthrequest Error: " + requestUrl + " " + error);
                    }
                }
                return(false);
            }

            parameters = HttpUtility.ParseQueryString(content);

            oauth_token  = parameters["oauth_token"];
            oauth_secret = parameters["oauth_token_secret"];
            switch (type)
            {
            case OAuthTokenType.YAHOO:
                guid = parameters["xoauth_yahoo_guid"];
                break;

            default:
                break;
            }

            return(true);
        }
Esempio n. 9
0
        // Private Methods (3) 

        private static IDictionary <string, string> ExtractVarsFromQueryString(IEnumerable <char> queryStr)
        {
            var result = new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer());

            try
            {
                var coll = BclHttpUtility.ParseQueryString(queryStr.AsString() ?? string.Empty);
                foreach (var key in coll.AllKeys)
                {
                    result[key ?? string.Empty] = coll[key];
                }
            }
            catch
            {
                // ignore
            }

            return(result);
        }
Esempio n. 10
0
        public virtual void GetAccessToken(OAuthRequestToken requestToken, string verifier, Action <OAuthAccessToken, TwitterResponse> action)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token          = requestToken.Token,
                TokenSecret    = requestToken.TokenSecret,
                Verifier       = verifier
            };

            var request = _accessTokenQuery.Invoke(args);

            _oauth.BeginRequest(request, (req, resp, state) =>
            {
                Exception exception;
                var entity = TryAsyncResponse(() =>
                {
                    if (resp == null || resp.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        return(null);
                    }

                    var query       = HttpUtility.ParseQueryString(resp.Content);
                    var accessToken = new OAuthAccessToken
                    {
                        Token       = query["oauth_token"] ?? "?",
                        TokenSecret = query["oauth_token_secret"] ?? "?",
                        UserId      = Convert.ToInt32(query["user_id"] ?? "0"),
                        ScreenName  = query["screen_name"] ?? "?"
                    };
                    return(accessToken);
                },
                                              out exception);

                action(entity, new TwitterResponse(resp, exception));
            }
                                );
        }
Esempio n. 11
0
        public virtual void GetRequestToken(string callback, Action <OAuthRequestToken, TwitterResponse> action)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret
            };

            var request = _requestTokenQuery.Invoke(args);

            if (!callback.IsNullOrBlank())
            {
                request.AddParameter("oauth_callback", callback);
            }

            _oauth.BeginRequest(request,
                                (req, resp, state) =>
            {
                Exception exception;
                var entity = TryAsyncResponse(() =>
                {
                    if (resp == null || resp.StatusCode != HttpStatusCode.OK)
                    {
                        return(null);
                    }
                    var query        = HttpUtility.ParseQueryString(resp.Content);
                    var requestToken = new OAuthRequestToken
                    {
                        Token                  = query["oauth_token"] ?? "?",
                        TokenSecret            = query["oauth_token_secret"] ?? "?",
                        OAuthCallbackConfirmed = Convert.ToBoolean(query["oauth_callback_confirmed"] ?? "false")
                    };
                    return(requestToken);
                },
                                              out exception);

                action(entity, new TwitterResponse(resp, exception));
            });
        }
Esempio n. 12
0
 public string GetOldOAuthAuthenticationUrl()
 {
     return(WebUtilities.GetUrl(HttpContext.Current.Request, "ViewPage.aspx",
                                HttpUtility.ParseQueryString("Id=3b22f0ff-034a-48da-8758-a0660e5a26ff")));
 }
Esempio n. 13
0
 private static NameValueCollection ParseQueryParameters(Uri uri)
 {
     return(HttpUtility.ParseQueryString(uri.Query));
 }
Esempio n. 14
0
        public bool GetRequestToken()
        {
            BuildRequestUrl();

            string      content;
            WebResponse response;

            try
            {
                var request = WebRequest.Create(requestUrl);
                request.Method = "GET";
                response       = request.GetResponse();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                response = ex.Response;
                if (response != null)
                {
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        var error = sr.ReadToEnd();
                        Syslog.Write("oauthrequest Error: " + requestUrl + " " + error);
                    }
                }
                return(false);
            }

            parameters = HttpUtility.ParseQueryString(content);

            oauth_token  = parameters["oauth_token"];
            oauth_secret = parameters["oauth_token_secret"];
            switch (type)
            {
            case OAuthTokenType.YAHOO:
                authorize_url = HttpUtility.UrlDecode(parameters["xoauth_request_auth_url"]);
                break;

            case OAuthTokenType.ETSY:
                authorize_url = HttpUtility.UrlDecode(parameters["login_url"]);
                break;

            case OAuthTokenType.TRADEME:
#if DEBUG
                authorize_url = "https://secure.tmsandbox.co.nz/Oauth/Authorize?oauth_token=" + oauth_token;
#else
                authorize_url = "https://secure.trademe.co.nz/Oauth/Authorize?oauth_token=" + oauth_token;
#endif
                break;

            default:
                throw new NotImplementedException();
                break;
            }
            if (String.IsNullOrEmpty(oauth_token) || String.IsNullOrEmpty(oauth_secret) || String.IsNullOrEmpty(authorize_url))
            {
                Syslog.Write(String.Format("{0} OAuth fail", type));
                return(false);
            }
            return(true);
        }
Esempio n. 15
0
        public Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = "")
        {
            if (!interfaceHttpMethods.ContainsKey(methodName))
            {
                throw new ArgumentException("Method must be defined and have an HTTP Method attribute");
            }
            var restMethod = interfaceHttpMethods[methodName];

            return(paramList => {
                var ret = new HttpRequestMessage()
                {
                    Method = restMethod.HttpMethod,
                };

                foreach (var header in restMethod.Headers)
                {
                    setHeader(ret, header.Key, header.Value);
                }

                string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath;
                var queryParamsToAdd = new Dictionary <string, string>();

                for (int i = 0; i < paramList.Length; i++)
                {
                    if (restMethod.ParameterMap.ContainsKey(i))
                    {
                        urlTarget = Regex.Replace(
                            urlTarget,
                            "{" + restMethod.ParameterMap[i] + "}",
                            settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]),
                            RegexOptions.IgnoreCase);
                        continue;
                    }

                    if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i)
                    {
                        var streamParam = paramList[i] as Stream;
                        var stringParam = paramList[i] as string;

                        if (streamParam != null)
                        {
                            ret.Content = new StreamContent(streamParam);
                        }
                        else if (stringParam != null)
                        {
                            ret.Content = new StringContent(stringParam);
                        }
                        else
                        {
                            switch (restMethod.BodyParameterInfo.Item1)
                            {
                            case BodySerializationMethod.UrlEncoded:
                                ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i]));
                                break;

                            case BodySerializationMethod.Json:
                                ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json");
                                break;
                            }
                        }

                        continue;
                    }


                    if (restMethod.HeaderParameterMap.ContainsKey(i))
                    {
                        setHeader(ret, restMethod.HeaderParameterMap[i], paramList[i]);
                    }
                    else
                    {
                        if (paramList[i] != null)
                        {
                            queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]);
                        }
                    }
                }

                // NB: The URI methods in .NET are dumb. Also, we do this
                // UriBuilder business so that we preserve any hardcoded query
                // parameters as well as add the parameterized ones.
                var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget));
                var query = HttpUtility.ParseQueryString(uri.Query ?? "");
                foreach (var kvp in queryParamsToAdd)
                {
                    query.Add(kvp.Key, kvp.Value);
                }

                if (query.HasKeys())
                {
                    var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x]));
                    uri.Query = String.Join("&", pairs);
                }
                else
                {
                    uri.Query = null;
                }

                ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative);
                return ret;
            });
        }
        Func <object[], HttpRequestMessage> buildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken)
        {
            if (!interfaceHttpMethods.ContainsKey(methodName))
            {
                throw new ArgumentException("Method must be defined and have an HTTP Method attribute");
            }
            var restMethod = interfaceHttpMethods[methodName];

            return(paramList => {
                // make sure we strip out any cancelation tokens
                if (paramsContainsCancellationToken)
                {
                    paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray();
                }

                var ret = new HttpRequestMessage {
                    Method = restMethod.HttpMethod,
                };

                // set up multipart content
                MultipartFormDataContent multiPartContent = null;
                if (restMethod.IsMultipart)
                {
                    multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
                    ret.Content = multiPartContent;
                }

                string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath;
                var queryParamsToAdd = new Dictionary <string, string>();
                var headersToAdd = new Dictionary <string, string>(restMethod.Headers);

                for (int i = 0; i < paramList.Length; i++)
                {
                    // if part of REST resource URL, substitute it in
                    if (restMethod.ParameterMap.ContainsKey(i))
                    {
                        urlTarget = Regex.Replace(
                            urlTarget,
                            "{" + restMethod.ParameterMap[i] + "}",
                            settings.UrlParameterFormatter
                            .Format(paramList[i], restMethod.ParameterInfoMap[i])
                            .Replace("/", "%2F"),
                            RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                        continue;
                    }

                    // if marked as body, add to content
                    if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i)
                    {
                        var streamParam = paramList[i] as Stream;
                        var stringParam = paramList[i] as string;
                        var httpContentParam = paramList[i] as HttpContent;

                        if (httpContentParam != null)
                        {
                            ret.Content = httpContentParam;
                        }
                        else if (streamParam != null)
                        {
                            ret.Content = new StreamContent(streamParam);
                        }
                        else if (stringParam != null)
                        {
                            ret.Content = new StringContent(stringParam);
                        }
                        else
                        {
                            switch (restMethod.BodyParameterInfo.Item1)
                            {
                            case BodySerializationMethod.UrlEncoded:
                                ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i]));
                                break;

                            case BodySerializationMethod.Json:
                                ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json");
                                break;
                            }
                        }

                        continue;
                    }

                    // if header, add to request headers
                    if (restMethod.HeaderParameterMap.ContainsKey(i))
                    {
                        headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null
                            ? paramList[i].ToString()
                            : null;
                        continue;
                    }

                    // ignore nulls
                    if (paramList[i] == null)
                    {
                        continue;
                    }

                    // for anything that fell through to here, if this is not
                    // a multipart method, add the parameter to the query string
                    if (!restMethod.IsMultipart)
                    {
                        queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]);
                        continue;
                    }

                    // we are in a multipart method, add the part to the content
                    // the parameter name should be either the attachment name or the parameter name (as fallback)
                    string itemName;
                    string parameterName;

                    Tuple <string, string> attachment;
                    if (!restMethod.AttachmentNameMap.TryGetValue(i, out attachment))
                    {
                        itemName = restMethod.QueryParameterMap[i];
                        parameterName = itemName;
                    }
                    else
                    {
                        itemName = attachment.Item1;
                        parameterName = attachment.Item2;
                    }


                    // Check to see if it's an IEnumerable
                    var itemValue = paramList[i];
                    var enumerable = itemValue as IEnumerable <object>;
                    var typeIsCollection = false;

                    if (enumerable != null)
                    {
                        Type tType = null;
                        var eType = enumerable.GetType();
                        if (eType.GetTypeInfo().ContainsGenericParameters)
                        {
                            tType = eType.GenericTypeArguments[0];
                        }
                        else if (eType.IsArray)
                        {
                            tType = eType.GetElementType();
                        }

                        // check to see if it's one of the types we support for multipart:
                        // FileInfo, Stream, string or byte[]
                        if (tType == typeof(Stream) ||
                            tType == typeof(string) ||
                            tType == typeof(byte[])
#if !NETFX_CORE
                            || tType == typeof(FileInfo)
#endif
                            )
                        {
                            typeIsCollection = true;
                        }
                    }

                    if (typeIsCollection)
                    {
                        foreach (var item in enumerable)
                        {
                            addMultipartItem(multiPartContent, itemName, parameterName, item);
                        }
                    }
                    else
                    {
                        addMultipartItem(multiPartContent, itemName, parameterName, itemValue);
                    }
                }

                // NB: We defer setting headers until the body has been
                // added so any custom content headers don't get left out.
                foreach (var header in headersToAdd)
                {
                    setHeader(ret, header.Key, header.Value);
                }

                // NB: The URI methods in .NET are dumb. Also, we do this
                // UriBuilder business so that we preserve any hardcoded query
                // parameters as well as add the parameterized ones.
                var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget));
                var query = HttpUtility.ParseQueryString(uri.Query ?? "");
                foreach (var kvp in queryParamsToAdd)
                {
                    query.Add(kvp.Key, kvp.Value);
                }

                if (query.HasKeys())
                {
                    var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x]));
                    uri.Query = String.Join("&", pairs);
                }
                else
                {
                    uri.Query = null;
                }

                ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative);
                return ret;
            });
        }
Esempio n. 17
0
        public Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = "")
        {
            if (!interfaceHttpMethods.ContainsKey(methodName))
            {
                throw new ArgumentException("Method must be defined and have an HTTP Method attribute");
            }
            var restMethod = interfaceHttpMethods[methodName];

            return(paramList => {
                var ret = new HttpRequestMessage {
                    Method = restMethod.HttpMethod,
                };

                // set up multipart content
                MultipartFormDataContent multiPartContent = null;
                if (restMethod.IsMultipart)
                {
                    multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
                    ret.Content = multiPartContent;
                }

                string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath;
                var queryParamsToAdd = new Dictionary <string, string>();
                var headersToAdd = new Dictionary <string, string>(restMethod.Headers);

                for (int i = 0; i < paramList.Length; i++)
                {
                    // if part of REST resource URL, substitute it in
                    if (restMethod.ParameterMap.ContainsKey(i))
                    {
                        urlTarget = Regex.Replace(
                            urlTarget,
                            "{" + restMethod.ParameterMap[i] + "}",
                            settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]),
                            RegexOptions.IgnoreCase);
                        continue;
                    }

                    // if marked as body, add to content
                    if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i)
                    {
                        var streamParam = paramList[i] as Stream;
                        var stringParam = paramList[i] as string;
                        var httpContentParam = paramList[i] as HttpContent;

                        if (httpContentParam != null)
                        {
                            ret.Content = httpContentParam;
                        }
                        else if (streamParam != null)
                        {
                            ret.Content = new StreamContent(streamParam);
                        }
                        else if (stringParam != null)
                        {
                            ret.Content = new StringContent(stringParam);
                        }
                        else
                        {
                            switch (restMethod.BodyParameterInfo.Item1)
                            {
                            case BodySerializationMethod.UrlEncoded:
                                ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i]));
                                break;

                            case BodySerializationMethod.Json:
                                ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json");
                                break;
                            }
                        }

                        continue;
                    }

                    // if header, add to request headers
                    if (restMethod.HeaderParameterMap.ContainsKey(i))
                    {
                        headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null
                            ? paramList[i].ToString()
                            : null;
                        continue;
                    }

                    // ignore nulls
                    if (paramList[i] == null)
                    {
                        continue;
                    }

                    // for anything that fell through to here, if this is not
                    // a multipart method, add the parameter to the query string
                    if (!restMethod.IsMultipart)
                    {
                        queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]);
                        continue;
                    }

                    // we are in a multipart method, add the part to the content
                    // the parameter name should be either the attachment name or the parameter name (as fallback)
                    string itemName;
                    if (!restMethod.AttachmentNameMap.TryGetValue(i, out itemName))
                    {
                        itemName = restMethod.QueryParameterMap[i];
                    }
                    addMultipartItem(multiPartContent, itemName, paramList[i]);
                }

                // NB: We defer setting headers until the body has been
                // added so any custom content headers don't get left out.
                foreach (var header in headersToAdd)
                {
                    setHeader(ret, header.Key, header.Value);
                }

                // NB: The URI methods in .NET are dumb. Also, we do this
                // UriBuilder business so that we preserve any hardcoded query
                // parameters as well as add the parameterized ones.
                var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget));
                var query = HttpUtility.ParseQueryString(uri.Query ?? "");
                foreach (var kvp in queryParamsToAdd)
                {
                    query.Add(kvp.Key, kvp.Value);
                }

                if (query.HasKeys())
                {
                    var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x]));
                    uri.Query = String.Join("&", pairs);
                }
                else
                {
                    uri.Query = null;
                }

                ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative);
                return ret;
            });
        }