Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="authParameters"></param>
        /// <param name="httpMethod"></param>
        /// <param name="contentType"></param>
        /// <param name="bodyStream"></param>
        /// <returns></returns>
        protected virtual HttpWebRequest CreateRequest(Uri requestUri, OAuthParameters authParameters, string httpMethod, string contentType, System.IO.Stream bodyStream)
        {
            NameValueCollection requestSpecificParameters = new NameValueCollection(authParameters.AdditionalParameters);

            if (!this.Service.UseAuthorizationHeader)
            {
                ////The OAuth params need to be added either into the querystring or into the post body.
                requestSpecificParameters.Add(authParameters.OAuthRequestParams());
            }

            if (Constants.HttpPostUrlEncodedContentTypeRegex.IsMatch(contentType) && bodyStream == null)
            {
                ////All the requestSpecificParameters need to be encoded into the body bytes
                string body = Rfc3986.EncodeAndJoin(requestSpecificParameters);
                bodyStream = new MemoryStream(Encoding.ASCII.GetBytes(body));
            }
            else
            {
                ////They go into the querystring.
                string query = Rfc3986.EncodeAndJoin(requestSpecificParameters);

                if (!string.IsNullOrEmpty(query))
                {
                    UriBuilder mutableRequestUri = new UriBuilder(requestUri);
                    if (string.IsNullOrEmpty(mutableRequestUri.Query))
                    {
                        mutableRequestUri.Query = query;
                    }
                    else
                    {
                        mutableRequestUri.Query = mutableRequestUri.Query.Substring(1) + "&" + query;
                    }

                    requestUri = mutableRequestUri.Uri;
                }
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);

            request.Method = httpMethod;

            if (this.Service.UseAuthorizationHeader)
            {
                request.Headers.Add(HttpRequestHeader.Authorization, authParameters.ToHeaderFormat());
            }

            if (!String.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;

                if (bodyStream != null)
                {
                    if (bodyStream.CanSeek)
                    {
                        request.ContentLength = bodyStream.Length;
                    }

                    StreamCopier.CopyTo(bodyStream, request.GetRequestStream());
                }
            }

            return(request);
        }