Beispiel #1
0
        public HttpClient(string endpoint, HttpVerb httpVerb, NameValueCollection headers, string contentType, string parameters)
        {
            try
            {
                this.Request = (HttpWebRequest)WebRequest.Create(endpoint);
                this.Request.ContentLength = 0;
                this.Request.ContentType = contentType.ToString();
                this.Request.Method = httpVerb.ToString();

                if (headers != null)
                {
                    foreach (var key in headers.AllKeys)
                    {
                        this.Request.Headers.Add(key, headers[key]);
                    }
                }

                if (this.Request.Method == HttpVerb.POST.ToString() && !String.IsNullOrEmpty(parameters))
                {
                    var encoding = new UTF8Encoding();
                    var bytes = Encoding.GetEncoding("utf-8").GetBytes(parameters);

                    this.Request.ContentLength = bytes.Length;

                    using (var writeStream = Request.GetRequestStream())
                    {
                        writeStream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException(String.Format("Create WebRequest Error: {0}", ex.Message));
            }
        }
Beispiel #2
0
        /// <summary>
        /// Make an HTTP request, with the given query args
        /// </summary>
        /// <param name="url">The URL of the request</param>
        /// <param name="httpVerb">The HTTP verb to use</param>
        /// <param name="argument">String thar represents the request data, must be in JSON format</param>
        private static string MakeRequest(Uri url, HttpVerb httpVerb, string argument = null)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = httpVerb.ToString();
            request.ContentType = "application/json";

            if (httpVerb == HttpVerb.POST)
            {
                var encoding = new ASCIIEncoding();
                var postDataBytes = new byte[0];
                if (argument != null)
                {
                    postDataBytes = encoding.GetBytes(argument);
                }

                request.ContentLength = postDataBytes.Length;

                var requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var reader = new StreamReader(response.GetResponseStream());
                    return reader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                throw new CoticulaApiException("Server Error", e.Message);
            }
        }
 public RestWebRequest(Uri uri, HttpVerb verb)
 {
     _baseRequest = new RestRequest(HttpWebRequest.Create(uri));
     _baseRequest.Method = verb.ToString();
     InitRequest();
 }
Beispiel #4
0
        /// <summary>
        /// Make an HTTP request, with the given query args
        /// </summary>
        /// <param name="url">The URL of the request</param>
        /// <param name="httpVerb">The HTTP verb to use</param>
        /// <param name="args">Dictionary of key/value pairs that represents
        /// the key/value pairs for the request</param>
        /// <param name="contentType"></param>
        /// <exception cref="FacebookApiException"></exception>
        /// <exception cref="SecurityException"></exception>
        internal string Request(string url, HttpVerb httpVerb, Dictionary<string, string> args, out string contentType)
        { 
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.Get)
            {
                url = url+ (url.Contains("?") ? "&" : "?") + EncodeDictionary(args);
            }

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = Proxy;
            request.Timeout = (int)Timeout.TotalMilliseconds;
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, Culture.IetfLanguageTag.ToLowerInvariant());
            request.Accept = "text/javascript";
            request.Method = httpVerb.ToString();

            if (httpVerb == HttpVerb.Post)
            {
                string postData = EncodeDictionary(args);
                byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataBytes.Length;

                try
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                    }
                }
                catch(WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                        throw OperationTimeout(ex);

                    throw;
                }
                catch (Exception ex)
                {
                    throw TransportError(ex);
                }
            }

            HttpWebResponse response;
            try
            {
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    contentType = ExtractContentType(response);
                    return new StreamReader(response.GetResponseStream()).ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)ex.Response;
                    contentType = ExtractContentType(response);

                    if (contentType == "text/javascript")
                    {
                        using (response)
                        {
                            return new StreamReader(response.GetResponseStream()).ReadToEnd();
                        }
                    }
                }

                throw TransportError(ex);
            }
            catch (Exception ex)
            {
                throw TransportError(ex);
            }
        }
        /// <summary>
        /// Make an HTTP request, with the given query args
        /// </summary>
        /// <param name="url">The URL of the request</param>
        /// <param name="verb">The HTTP verb to use</param>
        /// <param name="args">Dictionary of key/value pairs that represents
        /// the key/value pairs for the request</param>
        private string MakeRequest(Uri url, HttpVerb httpVerb,
            Dictionary<string, string> args)
        {
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
            {
                url = new Uri(url.ToString() + EncodeDictionary(args, true));
            }

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = httpVerb.ToString();

            if (httpVerb == HttpVerb.POST)
            {
                string postData = EncodeDictionary(args, false);

                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] postDataBytes = encoding.GetBytes(postData);

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response
                        = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader
                        = new StreamReader(response.GetResponseStream());

                    return reader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                throw new FacebookAPIException("Server Error", e.Message);
            }
        }
Beispiel #6
0
        // The Actual Request Method
        public static string MakeRequest(string uri, string parameters, HttpVerb method, string postData, CookieContainer cookieContainer, string userAgent, string contentType, WebHeaderCollection customHeaders)
        {
            try
            {
                // Create request and setup Headers
                var request = WebRequest.Create(uri + parameters) as HttpWebRequest;

                request.Method = method.ToString();
                request.UserAgent = userAgent;
                request.CookieContainer = cookieContainer;
                //request.Accept = "*/*";

                // Add Custom Headers if we have some, this includes our Authentication Header
                if (customHeaders != null && customHeaders.Count > 0)
                {
                    // NOTE: You cannot add the following Special Headers - http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx
                    request.Headers.Add(customHeaders);
                }

                #region HTTP Authentication Methods
                // Add a Custom Auth Header if we have one.
                // if (!string.IsNullOrEmpty(authHeader)) { request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authHeader); }

                // Authentication using a Credential Cache
                // request.Credentials = GetCredential(uri, "username", "password");

                // Manual Basic Authentication
                // string username = "******";
                // string password = "******";
                // string encoded = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
                // request.Headers.Add("Authorization", "Basic " + encoded);
                #endregion

                // Post Data
                if (method == HttpVerb.POST)
                {
                    // HACK: The Android Version Requires a Content Length Header even if the post data is null
                    request.ContentLength = 0;

                    if (!string.IsNullOrEmpty(postData))
                    {
                        var bytes = Encoding.UTF8.GetBytes(postData);
                        request.ContentType = contentType;
                        request.ContentLength = bytes.Length;

                        using (var requestStream = request.GetRequestStream())
                        {
                            requestStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }


                using (var response = (HttpWebResponse)request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                {
                    // Throw an Exception on Error
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
                    }

                    // TODO: Is this check necessary? let it throw an exception if there is no response Stream
                    string responseText = string.Empty;
                    if (responseStream != null)
                    {
                        using (var sr = new StreamReader(responseStream)) { responseText = sr.ReadToEnd(); }
                    }

                    // Done, return the response as Text for further processing.
                    return responseText;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
Beispiel #7
0
		// eo GetStringResponse

		/// <summary>
		/// Gets the string response from the passed endpoint.
		/// </summary>
		/// <returns>The string response, if any.</returns>
		/// <param name="url">Endpoint URL.</param>
		/// <param name="verb">HTTP Verb.</param>
		/// <param name="authToken">Auth token, if any.</param>
		/// <param name="requestBody">Request body.</param>
		/// <param name="format">Request Format.</param>
		/// <param name="encoding">Request Encoding.</param>
		/// <param name="additionalHeaders">Additional headers.</param>
		public async Task<WebServiceStringResult> GetStringResponse (
			String url,
			HttpVerb verb,
			String authToken,
			AuthorizationType authType = AuthorizationType.NOT_APPLICABLE,
			String requestBody = null,
			RequestDataFormatType format = RequestDataFormatType.JSON,
			RequestEncodingType encoding = RequestEncodingType.UTF8,
			List<HttpRequestHeader> additionalHeaders = null
		)
		{

			// Set up the call details.
			if (String.IsNullOrWhiteSpace (url))
				throw new ArgumentException ("URL cannot be null or whitespace.");
			else
				this.EndpointUri = new Uri (url);
			this.RequestDataFormat = format;
			this.ResponseDataFormat = ResponseDataFormatType.JSON;
			this.RequestEncoding = encoding;
			this.AdditionalHeaders = additionalHeaders;
			this.RequestBody = requestBody;
			if (String.IsNullOrWhiteSpace (authToken)) {
				this.AuthenticationToken = null;
				this.AuthenticationTokenType = AuthorizationType.NOT_APPLICABLE;
			} else {
				this.AuthenticationToken = authToken;
				this.AuthenticationTokenType = authType;
			}

			// Make the call and return the result.
			switch (verb) {
			case HttpVerb.GET:
				return await GetCall ();
			case HttpVerb.POST:
				return await PostCall ();
			case HttpVerb.PUT:
				return await PutCall ();
			case HttpVerb.DELETE:
				return await DeleteCall ();
			default:
				throw new NotImplementedException (String.Format ("Support for verb {0} is not yet implemented.", verb.ToString ()));
			}

		}
Beispiel #8
0
        /// <summary>
        /// Make an HTTP request, with the given query args
        /// Added by Nicolas Nowinski (ThinkPlusPlus.com) to support Pictures on 7/18/2010.
        /// </summary>
        /// <param name="url">The URL of the request</param>
        /// <param name="verb">The HTTP verb to use</param>
        /// <param name="args">Dictionary of key/value pairs that represents
        /// the key/value pairs for the request</param>
        private byte[] MakeRequestImage(Uri url, HttpVerb httpVerb,
                                   Dictionary<string, string> args)
        {
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
            {
                url = new Uri(url.ToString() + EncodeDictionary(args, true));
            }

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = httpVerb.ToString();

            if (httpVerb == HttpVerb.POST)
            {
                string postData = EncodeDictionary(args, false);

                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] postDataBytes = encoding.GetBytes(postData);

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response
                        = request.GetResponse() as HttpWebResponse)
                {
                    //Credit goes to Greg Beech: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/13f919db-b9e0-4978-9bfe-16f0fcf2a51e

                    Stream reader = response.GetResponseStream();

                    MemoryStream cloneStream = new MemoryStream(0x1000);
                    byte[] buffer = new byte[0x1000];
                    int bytesInBuffer;
                    while ((bytesInBuffer = reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        cloneStream.Write(buffer, 0, bytesInBuffer);
                    }
                    cloneStream.Flush();
                    byte[] completeData = cloneStream.GetBuffer();

                    return completeData;
                    //return reader.BaseStream.();
                }
            }
            catch (WebException e)
            {
                throw new FacebookAPIException("Server Error", e.Message);
            }
        }
Beispiel #9
0
        private static void MakeRequest(string contentType, HttpVerb method, string url, object parameters, Action<WebHeaderCollection, Stream> successCallback, Action<WebException> failCallback)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters object cannot be null");
            }

            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException("url is empty");
            }
            

            try
            {
                /*
                 * Create new Request
                 */
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.CookieContainer = cookies;
                request.Method = method.ToString();
                

                

                /*
                 * Asynchronously get the response
                 */
                if (method == HttpVerb.Delete || method == HttpVerb.Post || method == HttpVerb.Put || method == HttpVerb.Patch)
                {
                    request.ContentType = contentType;
                    request.BeginGetRequestStream(new AsyncCallback((IAsyncResult callbackResult) =>
                    {                 
                        HttpWebRequest tmprequest = (HttpWebRequest)callbackResult.AsyncState;
                        Stream postStream;

                        postStream = tmprequest.EndGetRequestStream(callbackResult);


                        string postbody = "";

                        
                        postbody = Utils.SerializeQueryString(parameters);
                        

                        // Convert the string into a byte array. 
                        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postbody);

                        // Write to the request stream.
                        postStream.Write(byteArray, 0, byteArray.Length);
                        postStream.Flush();
                        postStream.Dispose();

                        // Start the asynchronous operation to get the response
                        tmprequest.BeginGetResponse(ProcessCallback(successCallback,failCallback), tmprequest);


                    }), request);
                }
                else if (method == HttpVerb.Get || method == HttpVerb.Head)
                {
                    request.BeginGetResponse(ProcessCallback(successCallback,failCallback), request);
                }
            }
            catch (WebException webEx)
            {
                failCallback(webEx);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Upload an array of files to a remote host using the HTTP post or put multipart method
        /// </summary>
        /// <param name="url">Target url</param>
        /// <param name="method">Request Method - POST or PUT</param>
        /// <param name="parameters">Parmaters</param>
        /// <param name="files">An array of files</param>
        /// <param name="successCallback">Funciton that is called on success</param>
        /// <param name="failCallback">Function that is called on failure</param>
        public static void Upload(string url, HttpVerb method, object parameters, NamedFileStream[] files, Action<WebHeaderCollection, Stream> successCallback,Action<WebException> failCallback)
        {
            if (method != HttpVerb.Post && method != HttpVerb.Put)
            {
                throw new ArgumentException("Request method must be POST or PUT");
            }

            try
            {
                /*
                 * Generate a random boundry string
                 */
                string boundary = RandomString(12);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.Method = method.ToString();
                request.ContentType = "multipart/form-data, boundary=" + boundary;
                request.CookieContainer = cookies;
     
                request.BeginGetRequestStream(new AsyncCallback((IAsyncResult asynchronousResult) =>
                {
                    /*
                     * Create a new request
                     */
                    HttpWebRequest tmprequest = (HttpWebRequest)asynchronousResult.AsyncState;

                    /*
                     * Get a stream that we can write to
                     */
                    Stream postStream = tmprequest.EndGetRequestStream(asynchronousResult);
                    string querystring = "\n";

                    /*
                     * Serialize parameters in multipart manner
                     */
                    #if NETFX_CORE
                    foreach (var property in parameters.GetType().GetTypeInfo().DeclaredProperties)
                    #else
                    foreach (var property in parameters.GetType().GetProperties())                    
                    #endif
                    {
                        querystring += "--" + boundary + "\n";
                        querystring += "content-disposition: form-data; name=\"" + System.Uri.EscapeDataString(property.Name) + "\"\n\n";
                        querystring += System.Uri.EscapeDataString(property.GetValue(parameters, null).ToString());
                        querystring += "\n";
                    }

                
                    /*
                     * Then write query string to the postStream
                     */
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(querystring);
                    postStream.Write(byteArray, 0, byteArray.Length);
                
                    /*
                     * A boundary string that we'll reuse to separate files
                     */ 
                    byte[] closing = System.Text.Encoding.UTF8.GetBytes("\n--" + boundary + "--\n");


                    /*
                     * Write each files to the postStream
                     */
                    foreach (NamedFileStream file in files)
                    {
                        /*
                         * A temporary buffer to hold the file stream
                         * Not sure if this is needed ???
                         */
                        Stream outBuffer = new MemoryStream();

                        /*
                         * Additional info that is prepended to the file
                         */
                        string qsAppend;
                        qsAppend = "--" + boundary + "\ncontent-disposition: form-data; name=\""+file.Name +"\"; filename=\"" + file.Filename + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
       
                        /*
                         * Read the file into the output buffer
                         */
                        StreamReader sr = new StreamReader(file.Stream);
                        outBuffer.Write(System.Text.Encoding.UTF8.GetBytes(qsAppend), 0, qsAppend.Length);

                        int bytesRead = 0;
                        byte[] buffer = new byte[4096];

                        while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            outBuffer.Write(buffer, 0, bytesRead);

                        }


                        /*
                         * Write the delimiter to the output buffer
                         */
                        outBuffer.Write(closing, 0, closing.Length);



                        /*
                         * Write the output buffer to the post stream using an intemediate byteArray
                         */
                        outBuffer.Position = 0;
                        byte[] tempBuffer = new byte[outBuffer.Length];
                        outBuffer.Read(tempBuffer, 0, tempBuffer.Length);
                        postStream.Write(tempBuffer, 0, tempBuffer.Length);
                        postStream.Flush();           
                    }

                
                    postStream.Flush();
                    postStream.Dispose();

                    tmprequest.BeginGetResponse(ProcessCallback(successCallback, failCallback), tmprequest);

                }), request);
            }
            catch (WebException webEx)
            {
                failCallback(webEx);
            }

        }
        /// <summary>
        /// Make an HTTP request, with the given query args
        /// </summary>
        private string MakeRequest(Uri url, HttpVerb httpVerb, List<KeyValuePair<string, string>> args, JSONObject body, ContentType contentType = ContentType.JSON)
        {
            // Prepare HTTP url
            url = PrepareUrl(url, AccessToken, args);

            // Set request
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = httpVerb.ToString();

            if ((httpVerb == HttpVerb.POST) || (httpVerb == HttpVerb.PUT))
            {
                // Prepare HTTP body
                string postData = EncodeBody(body, contentType);
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] postDataBytes = encoding.GetBytes(postData);

                // Set content type & length
                if (contentType == ContentType.JSON)
                {
                    request.ContentType = "application/json";
                }
                else
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                request.ContentLength = postDataBytes.Length;

                // Call API
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Read response data
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string responseBody = reader.ReadToEnd();

                    // Understand REST response
                    if (SuccessfulCall(response.StatusCode))
                    {
                        // Ok
                        return responseBody;
                    }
                    else
                    {
                        // Problem
                        try
                        {
                            // Try throwing a well-formed api error
                            JSONObject errorBody = JSONObject.CreateFromString(responseBody);
                            throw new RESTAPIException(errorBody.Dictionary["error"].Dictionary["type"].String, errorBody.Dictionary["error"].Dictionary["message"].String);
                        }
                        catch (RESTAPIException restEx)
                        {
                            throw restEx;  // this is a well-formed error message
                        }
                        catch
                        {
                            throw new RESTAPIException(response.StatusCode.ToString(), responseBody);  // this is not a well-formed message
                        }
                    }
                }
            }
            catch (WebException e)
            {
                throw new RESTAPIException("Server Error", e.Message);
            }
        }
        /// <summary>
        /// Make REST request.
        /// </summary>
        /// <param name="target">Target URL. Contains names of objects to be requested.</param>
        /// <param name="method">HTTP method. Reflects type of operation required [add/delete/get].</param>
        /// <param name="parameters">REST request parameters.</param>
        /// <param name="data">Data to send to server. Only appropriate when making POST request.</param>
        /// <returns>Response string representation</returns>
        public string MakeRequest(string target, HttpVerb method = HttpVerb.Get, Dictionary<string, string> parameters = null, string data = null)
        {
            if ((parameters != null) && parameters.Any())
            {
                target += "?";

                // Append all URL parameters
                parameters.Aggregate(target, (current, parameter) => current + string.Format("{0}={1}", parameter.Key, parameter.Value));
            }

            var request = (HttpWebRequest)WebRequest.Create(target);

            // Set request header
            request.Method = method.ToString().ToUpper();
            request.ContentLength = 0;
            request.ContentType = "text\\xml";

            if (target.Contains("https://"))
            {
                request.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
                {
                    return certificate.Equals(Certificate);
                };
            }

            // Set authorization header
            var credentials = Convert.ToBase64String(Encoding.GetBytes(string.Format("{0}:{1}", UserName, Password)));
            request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + credentials);

            // Append post data
            if (!string.IsNullOrEmpty(data) && ((method == HttpVerb.Post) || (method == HttpVerb.Put)))
            {
                var bytes = Encoding.GetBytes(data);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            // Make request
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }

            RequestCounter++;

            if (response != null)
            {
                switch (response.StatusCode)
                {
                    case HttpStatusCode.Created:
                    case HttpStatusCode.OK:
                        // Read the response
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (var reader = new StreamReader(responseStream))
                                {
                                    return reader.ReadToEnd();
                                }
                            }

                            return null;
                        }

                    case HttpStatusCode.BadRequest:
                        // Build error string
                        var error = new StringBuilder();
                        error.AppendLine("Bad request. The data was: " + data);
                        throw new InvalidOperationException(error.ToString());

                    case HttpStatusCode.NotFound:
                        throw new InstanceNotFoundException("Object doesn't exist.");

                    default:
                        var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                        throw new ApplicationException(message);
                }
            }

            return null;
        }
Beispiel #13
0
        internal IAsyncResult BeginRequest(
            string url,
            HttpVerb httpVerb,
            Dictionary<string, string> args,
            AsyncCallback cb, object state)
        {
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.Get)
                url = url+ (url.Contains("?") ? "&" : "?") + EncodeDictionary(args);

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = Proxy;
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, Culture.IetfLanguageTag.ToLowerInvariant());
            request.Method = httpVerb.ToString();
            var tar = new TypedAsyncResult<ResponseData>(cb, state);

            Action beginGetResp = () => request.BeginGetResponse(tar.AsSafe(gr =>
            {
                HttpWebResponse resp;
                Stream respStm;
                string contentType;
                try
                {
                    resp = (HttpWebResponse)request.EndGetResponse(gr);
                    contentType = ExtractContentType(resp);
                    respStm = resp.GetResponseStream();
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        resp = (HttpWebResponse)ex.Response;
                        contentType = ExtractContentType(resp);

                        if (contentType == "text/javascript")
                        {
                            respStm = resp.GetResponseStream();
                            goto ok;
                        }
                    }

                    throw TransportError(ex);
                }

                ok: var buf = new byte[4096];
                var ms = new MemoryStream(buf.Length);

                AsyncCallback cbr = null;
                cbr = tar.AsSafe(br =>
                {
                    int cnt = respStm.EndRead(br);
                    if (cnt == 0)
                    {
                        if (!tar.IsCompleted)
                        {
                            ((IDisposable)resp).Dispose();
                            ms.Seek(0, SeekOrigin.Begin);
                            tar.Complete(new ResponseData
                            {
                                Json = Encoding.UTF8.GetString(ms.ToArray()),
                                ContentType = contentType,
                            }, false);
                        }
                    }
                    else
                    {
                        ms.Write(buf, 0, cnt);
                        respStm.BeginRead(buf, 0, buf.Length, cbr, null);
                    }
                }, ex => ((IDisposable)resp).Dispose());

                respStm.BeginRead(buf, 0, buf.Length, cbr, null);
            }), null);

            try
            {
                if (httpVerb == HttpVerb.Post)
                {
                    string postData = EncodeDictionary(args);
                    byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = postDataBytes.Length;

                    request.BeginGetRequestStream(tar.AsSafe(rar =>
                    {
                        Stream rqStm = request.EndGetRequestStream(rar);
                        rqStm.BeginWrite(postDataBytes, 0, postDataBytes.Length, tar.AsSafe(wr =>
                        {
                            rqStm.EndWrite(wr);
                            beginGetResp();
                        }), null);
                    }), null);
                }
                else
                {
                    beginGetResp();
                }
            }
            catch (Exception ex)
            {
                if (!tar.IsCompleted)
                    tar.Complete(true, ex);
            }

            return tar;
        }