Example #1
0
        public static void GetHttpWebResponse(Action <HttpWebResponse> callback, Action <Exception> onError, IRestApi client, string url, HttpMethod method, params IApiParameter[] parameters)
        {
            List <ApiParameter>     simpleParameters = parameters.OfType <ApiParameter>().ToListOrEmpty();
            List <ApiMimeParameter> mimeParameters   = parameters.OfType <ApiMimeParameter>().ToListOrEmpty();
            string         fullUrl     = null;
            HttpWebRequest httpRequest = null;
            StringBuilder  postData    = null;

            //Allow the Client to authenticate, add parameters, etc., and return the Full URL to use.
            try
            {
                fullUrl = client.BeforeSendRequest(url, method, simpleParameters, mimeParameters);
            }
            catch (Exception ex) { onError(ex); return; }

            //If the URL was not set by the this.Client, build it here.
            if (string.IsNullOrEmpty(fullUrl))
            {
                fullUrl = url;

                //Build the parameter string, if necessary.
                if (simpleParameters.Count > 0)
                {
                    string parameterString = string.Join("&", simpleParameters.Where(p => p.IsValid).Select(p => p.ToString()).ToArray());

                    if (!string.IsNullOrEmpty(parameterString))
                    {
                        fullUrl += "?" + parameterString;
                    }
                }
            }

            //Set the request options.
            httpRequest           = (HttpWebRequest)WebRequest.Create(fullUrl);
            httpRequest.UserAgent = client.ApplicationName;
            httpRequest.Method    = method.ToString();

            //Add any attachments.
            if (mimeParameters.Count > 0 && mimeParameters.Any(p => p.IsValid))
            {
                string boundary = DateTimeUtil.Now.Ticks.ToString();

                postData = new StringBuilder();

                foreach (ApiMimeParameter parameter in mimeParameters.Where(p => p.IsValid))
                {
                    parameter.Write(postData, boundary);
                }

                //Set additional request options.
                httpRequest.Method      = HttpMethod.POST.ToString();
                httpRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

#if (!WINDOWS_PHONE)
                httpRequest.ContentLength = postData.Length;
#endif

                //Write the data to the request stream (async). Which will then get the response (async).
                httpRequest.BeginGetRequestStream(GetRequestStreamCallback, new RequestState(httpRequest, postData.ToString(), callback, onError));
            }
            else
            {
                httpRequest.BeginGetResponse(GetResponseCallback, new RequestState(httpRequest, null, callback, onError));
            }
        }