示例#1
0
        private void ClearRequestData()
        {
            _content = null;

            _addedUrlParams = null;
            _addedParams = null;
            _addedMultipartContent = null;
            _addedHeaders = null;
        }
示例#2
0
        private HttpResponse SendRequest(HttpMethod method, Uri address,
            HttpContent content, bool reconnection = false)
        {
            _content = content;

            if (_tcpClient != null &&
                !_response.MessageBodyLoaded && !_response.HasError)
            {
                try
                {
                    _response.None();
                }
                catch (HttpException)
                {
                    Dispose();
                }
            }

            bool createdNewConnection = false;

            ProxyClient proxy = GetProxy();

            // Если нужно создать новое подключение.
            if (_tcpClient == null || Address.Port != address.Port ||
                !Address.Host.Equals(address.Host, StringComparison.OrdinalIgnoreCase) ||
                !Address.Scheme.Equals(address.Scheme, StringComparison.OrdinalIgnoreCase) ||
                _response.HasError || _currentProxy != proxy)
            {
                Address = address;
                _currentProxy = proxy;

                Dispose();
                CreateConnection();

                createdNewConnection = true;
            }
            else
            {
                Address = address;
            }

            #region Отправка запроса

            try
            {
                if (_content == null)
                {
                    _contentLength = 0;
                }
                else
                {
                    _contentLength = _content.CalculateContentLength();
                }

                byte[] startingLineBytes = Encoding.ASCII.GetBytes(GenerateStartingLine(method));
                byte[] headersBytes = Encoding.ASCII.GetBytes(GenerateHeaders(method));

                _bytesSent = 0;
                _totalBytesSent = startingLineBytes.Length + headersBytes.Length + _contentLength;

                _clientStream.Write(startingLineBytes, 0, startingLineBytes.Length);
                _clientStream.Write(headersBytes, 0, headersBytes.Length);

                // Отправляем тело сообщения, если оно не пустое.
                if (_content != null && _contentLength > 0)
                {
                    _content.WriteTo(_clientStream);
                }
            }
            catch (SecurityException ex)
            {
                throw NewHttpException(Resources.HttpException_FailedSendRequest, ex, HttpExceptionStatus.SendFailure);
            }
            catch (IOException ex)
            {
                // Если это не первый запрос и включены постоянные соединения и до этого не было переподключения,
                // то пробуем заново отправить запрос.
                if (!createdNewConnection && KeepAlive && !reconnection)
                {
                    Dispose();
                    return SendRequest(method, address, content, true);
                }

                throw NewHttpException(Resources.HttpException_FailedSendRequest, ex, HttpExceptionStatus.SendFailure);
            }

            #endregion

            #region Загрузка ответа

            try
            {
                _canReportBytesReceived = false;

                _bytesReceived = 0;
                _totalBytesReceived = _response.LoadResponse(method);

                _canReportBytesReceived = true;
            }
            catch (HttpException ex)
            {
                // Если был получен пустой ответ и до этого не было переподключения или
                // если это не первый запрос и включены постоянные соединения и до этого не было переподключения,
                // то пробуем заново отправить запрос.
                if ((ex.EmptyMessageBody && !reconnection) ||
                    (!createdNewConnection && KeepAlive && !reconnection))
                {
                    Dispose();
                    return SendRequest(method, address, content, true);
                }

                throw;
            }

            #endregion

            #region Проверка кода ответа

            if (!IgnoreProtocolErrors)
            {
                int statusCodeNum = (int)_response.StatusCode;

                if (statusCodeNum >= 400 && statusCodeNum < 500)
                {
                    throw new HttpException(string.Format(
                        Resources.HttpException_ClientError, statusCodeNum),
                        HttpExceptionStatus.ProtocolError, _response.StatusCode);
                }
                else if (statusCodeNum >= 500)
                {
                    throw new HttpException(string.Format(
                        Resources.HttpException_SeverError, statusCodeNum),
                        HttpExceptionStatus.ProtocolError, _response.StatusCode);
                }
            }

            #endregion

            #region Переадресация

            if (AllowAutoRedirect && _response.HasRedirect)
            {
                if (++_redirectionCount > _maximumAutomaticRedirections)
                {
                    throw NewHttpException(Resources.HttpException_LimitRedirections);
                }

                ClearRequestData();

                return SendRequest(HttpMethod.GET, _response.RedirectAddress, null);
            }

            _redirectionCount = 0;

            #endregion

            return _response;
        }
示例#3
0
        /// <summary>
        /// Отправляет GET-запрос HTTP-серверу.
        /// </summary>
        /// <param name="method">HTTP-метод запроса.</param>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="content">Контент, отправляемый HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <returns>Объект, предназначенный для приёма ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> является пустой строкой.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Raw(HttpMethod method, string address, HttpContent content = null)
        {
            #region Проверка параметров

            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            if (address.Length == 0)
            {
                throw ExceptionHelper.EmptyString("address");
            }

            #endregion

            var uri = new Uri(address, UriKind.RelativeOrAbsolute);

            return Raw(method, uri, content);
        }
示例#4
0
        /// <summary>
        /// Отправляет GET-запрос HTTP-серверу.
        /// </summary>
        /// <param name="method">HTTP-метод запроса.</param>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="content">Контент, отправляемый HTTP-серверу, или значение <see langword="null"/>.</param>
        /// <returns>Объект, предназначенный для приёма ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Raw(HttpMethod method, Uri address, HttpContent content = null)
        {
            #region Проверка параметров

            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            #endregion

            if (!address.IsAbsoluteUri)
            {
                address = CreateAbsoluteAddress(address);
            }
            else if (_addedUrlParams != null)
            {
                var uriBuilder = new UriBuilder(address);
                uriBuilder.Query = HttpHelper.ToQueryString(_addedUrlParams, true);

                address = uriBuilder.Uri;
            }

            if (!(method == HttpMethod.POST || method == HttpMethod.PUT))
            {
                content = null;
            }
            else if (content == null)
            {
                if (_addedParams != null)
                {
                    content = new FormUrlEncodedContent(_addedParams);
                }
                else if (_addedMultipartContent != null)
                {
                    content = _addedMultipartContent;
                }
            }

            try
            {
                return SendRequest(method, address, content);
            }
            finally
            {
                if (content != null)
                {
                    content.Dispose();
                }

                ClearRequestData();
            }
        } 
示例#5
0
        /// <summary>
        /// Отправляет POST-запрос HTTP-серверу.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="content">Контент, отправляемый HTTP-серверу.</param>
        /// <returns>Объект, предназначенный для приёма ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Значение параметра <paramref name="address"/> равно <see langword="null"/>.
        /// -или-
        /// Значение параметра <paramref name="content"/> равно <see langword="null"/>.
        /// </exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Post(Uri address, HttpContent content)
        {
            #region Проверка параметров

            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            #endregion

            return Raw(HttpMethod.POST, address, content);
        }