/// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(IHttpRequest request, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            string method = request.GetRequestLine().GetMethod();

            if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT"))
            {
                request.SetHeader(ProxyConnDirective, HTTP.ConnKeepAlive);
                return;
            }
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            // Obtain the client connection (required)
            RouteInfo route = clientContext.GetHttpRoute();

            if (route == null)
            {
                this.log.Debug("Connection route not set in the context");
                return;
            }
            if (route.GetHopCount() == 1 || route.IsTunnelled())
            {
                if (!request.ContainsHeader(HTTP.ConnDirective))
                {
                    request.AddHeader(HTTP.ConnDirective, HTTP.ConnKeepAlive);
                }
            }
            if (route.GetHopCount() == 2 && !route.IsTunnelled())
            {
                if (!request.ContainsHeader(ProxyConnDirective))
                {
                    request.AddHeader(ProxyConnDirective, HTTP.ConnKeepAlive);
                }
            }
        }
Example #2
0
 /// <exception cref="Org.Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if (request is HttpEntityEnclosingRequest)
     {
         if (this.overwrite)
         {
             request.RemoveHeaders(HTTP.TransferEncoding);
             request.RemoveHeaders(HTTP.ContentLen);
         }
         else
         {
             if (request.ContainsHeader(HTTP.TransferEncoding))
             {
                 throw new ProtocolException("Transfer-encoding header already present");
             }
             if (request.ContainsHeader(HTTP.ContentLen))
             {
                 throw new ProtocolException("Content-Length header already present");
             }
         }
         ProtocolVersion ver    = request.GetRequestLine().GetProtocolVersion();
         HttpEntity      entity = ((HttpEntityEnclosingRequest)request).GetEntity();
         if (entity == null)
         {
             request.AddHeader(HTTP.ContentLen, "0");
             return;
         }
         // Must specify a transfer encoding or a content length
         if (entity.IsChunked() || entity.GetContentLength() < 0)
         {
             if (ver.LessEquals(HttpVersion.Http10))
             {
                 throw new ProtocolException("Chunked transfer encoding not allowed for " + ver);
             }
             request.AddHeader(HTTP.TransferEncoding, HTTP.ChunkCoding);
         }
         else
         {
             request.AddHeader(HTTP.ContentLen, System.Convert.ToString(entity.GetContentLength
                                                                            ()));
         }
         // Specify a content type if known
         if (entity.GetContentType() != null && !request.ContainsHeader(HTTP.ContentType))
         {
             request.AddHeader(entity.GetContentType());
         }
         // Specify a content encoding if known
         if (entity.GetContentEncoding() != null && !request.ContainsHeader(HTTP.ContentEncoding
                                                                            ))
         {
             request.AddHeader(entity.GetContentEncoding());
         }
     }
 }
 /// <summary>
 /// Adds the header
 /// <code>"Accept-Encoding: gzip,deflate"</code>
 /// to the request.
 /// </summary>
 /// <exception cref="Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     if (!request.ContainsHeader("Accept-Encoding"))
     {
         request.AddHeader("Accept-Encoding", "gzip,deflate");
     }
 }
Example #4
0
 /// <exception cref="Org.Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if ((request is HttpEntityEnclosingRequest) && !request.ContainsHeader(HTTP.DateHeader
                                                                            ))
     {
         string httpdate = DateGenerator.GetCurrentDate();
         request.SetHeader(HTTP.DateHeader, httpdate);
     }
 }
        /// <exception cref="Org.Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(IHttpRequest request, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            string method = request.GetRequestLine().GetMethod();

            if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT"))
            {
                return;
            }
            if (!request.ContainsHeader(HTTP.ConnDirective))
            {
                // Default policy is to keep connection alive
                // whenever possible
                request.AddHeader(HTTP.ConnDirective, HTTP.ConnKeepAlive);
            }
        }
		/// <exception cref="Org.Apache.Http.HttpException"></exception>
		/// <exception cref="System.IO.IOException"></exception>
		public virtual void Process(IHttpRequest request, HttpContext context)
		{
			Args.NotNull(request, "HTTP request");
			HttpCoreContext corecontext = HttpCoreContext.Adapt(context);
			ProtocolVersion ver = request.GetRequestLine().GetProtocolVersion();
			string method = request.GetRequestLine().GetMethod();
			if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT") && ver.LessEquals(HttpVersion
				.Http10))
			{
				return;
			}
			if (!request.ContainsHeader(HTTP.TargetHost))
			{
				HttpHost targethost = corecontext.GetTargetHost();
				if (targethost == null)
				{
					HttpConnection conn = corecontext.GetConnection();
					if (conn is HttpInetConnection)
					{
						// Populate the context with a default HTTP host based on the
						// inet address of the target host
						IPAddress address = ((HttpInetConnection)conn).GetRemoteAddress();
						int port = ((HttpInetConnection)conn).GetRemotePort();
						if (address != null)
						{
							targethost = new HttpHost(address.GetHostName(), port);
						}
					}
					if (targethost == null)
					{
						if (ver.LessEquals(HttpVersion.Http10))
						{
							return;
						}
						else
						{
							throw new ProtocolException("Target host missing");
						}
					}
				}
				request.AddHeader(HTTP.TargetHost, targethost.ToHostString());
			}
		}
Example #7
0
 /// <exception cref="Org.Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if (!request.ContainsHeader(HTTP.UserAgent))
     {
         string     s       = null;
         HttpParams @params = request.GetParams();
         if (@params != null)
         {
             s = (string)@params.GetParameter(CoreProtocolPNames.UserAgent);
         }
         if (s == null)
         {
             s = this.userAgent;
         }
         if (s != null)
         {
             request.AddHeader(HTTP.UserAgent, s);
         }
     }
 }
Example #8
0
 /// <exception cref="Org.Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if (!request.ContainsHeader(HTTP.ExpectDirective))
     {
         if (request is HttpEntityEnclosingRequest)
         {
             ProtocolVersion ver    = request.GetRequestLine().GetProtocolVersion();
             HttpEntity      entity = ((HttpEntityEnclosingRequest)request).GetEntity();
             // Do not send the expect header if request body is known to be empty
             if (entity != null && entity.GetContentLength() != 0 && !ver.LessEquals(HttpVersion
                                                                                     .Http10))
             {
                 bool active = request.GetParams().GetBooleanParameter(CoreProtocolPNames.UseExpectContinue
                                                                       , this.activeByDefault);
                 if (active)
                 {
                     request.AddHeader(HTTP.ExpectDirective, HTTP.ExpectContinue);
                 }
             }
         }
     }
 }
 /// <exception cref="Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if (!request.ContainsHeader(HTTP.ExpectDirective))
     {
         if (request is HttpEntityEnclosingRequest)
         {
             ProtocolVersion ver    = request.GetRequestLine().GetProtocolVersion();
             HttpEntity      entity = ((HttpEntityEnclosingRequest)request).GetEntity();
             // Do not send the expect header if request body is known to be empty
             if (entity != null && entity.GetContentLength() != 0 && !ver.LessEquals(HttpVersion
                                                                                     .Http10))
             {
                 HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                               ));
                 RequestConfig config = clientContext.GetRequestConfig();
                 if (config.IsExpectContinueEnabled())
                 {
                     request.AddHeader(HTTP.ExpectDirective, HTTP.ExpectContinue);
                 }
             }
         }
     }
 }
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Apache.Http.HttpException"></exception>
        public virtual CloseableHttpResponse Execute(HttpRoute route, HttpRequestWrapper
                                                     request, HttpClientContext context, HttpExecutionAware execAware)
        {
            Args.NotNull(route, "HTTP route");
            Args.NotNull(request, "HTTP request");
            Args.NotNull(context, "HTTP context");
            AuthState targetAuthState = context.GetTargetAuthState();

            if (targetAuthState == null)
            {
                targetAuthState = new AuthState();
                context.SetAttribute(HttpClientContext.TargetAuthState, targetAuthState);
            }
            AuthState proxyAuthState = context.GetProxyAuthState();

            if (proxyAuthState == null)
            {
                proxyAuthState = new AuthState();
                context.SetAttribute(HttpClientContext.ProxyAuthState, proxyAuthState);
            }
            if (request is HttpEntityEnclosingRequest)
            {
                Proxies.EnhanceEntity((HttpEntityEnclosingRequest)request);
            }
            object            userToken   = context.GetUserToken();
            ConnectionRequest connRequest = connManager.RequestConnection(route, userToken);

            if (execAware != null)
            {
                if (execAware.IsAborted())
                {
                    connRequest.Cancel();
                    throw new RequestAbortedException("Request aborted");
                }
                else
                {
                    execAware.SetCancellable(connRequest);
                }
            }
            RequestConfig        config = context.GetRequestConfig();
            HttpClientConnection managedConn;

            try
            {
                int timeout = config.GetConnectionRequestTimeout();
                managedConn = connRequest.Get(timeout > 0 ? timeout : 0, TimeUnit.Milliseconds);
            }
            catch (Exception interrupted)
            {
                Sharpen.Thread.CurrentThread().Interrupt();
                throw new RequestAbortedException("Request aborted", interrupted);
            }
            catch (ExecutionException ex)
            {
                Exception cause = ex.InnerException;
                if (cause == null)
                {
                    cause = ex;
                }
                throw new RequestAbortedException("Request execution failed", cause);
            }
            context.SetAttribute(HttpClientContext.HttpConnection, managedConn);
            if (config.IsStaleConnectionCheckEnabled())
            {
                // validate connection
                if (managedConn.IsOpen())
                {
                    this.log.Debug("Stale connection check");
                    if (managedConn.IsStale())
                    {
                        this.log.Debug("Stale connection detected");
                        managedConn.Close();
                    }
                }
            }
            ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn
                                                               );

            try
            {
                if (execAware != null)
                {
                    execAware.SetCancellable(connHolder);
                }
                HttpResponse response;
                for (int execCount = 1; ; execCount++)
                {
                    if (execCount > 1 && !Proxies.IsRepeatable(request))
                    {
                        throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity."
                                                                );
                    }
                    if (execAware != null && execAware.IsAborted())
                    {
                        throw new RequestAbortedException("Request aborted");
                    }
                    if (!managedConn.IsOpen())
                    {
                        this.log.Debug("Opening connection " + route);
                        try
                        {
                            EstablishRoute(proxyAuthState, managedConn, route, request, context);
                        }
                        catch (TunnelRefusedException ex)
                        {
                            if (this.log.IsDebugEnabled())
                            {
                                this.log.Debug(ex.Message);
                            }
                            response = ex.GetResponse();
                            break;
                        }
                    }
                    int timeout = config.GetSocketTimeout();
                    if (timeout >= 0)
                    {
                        managedConn.SetSocketTimeout(timeout);
                    }
                    if (execAware != null && execAware.IsAborted())
                    {
                        throw new RequestAbortedException("Request aborted");
                    }
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Executing request " + request.GetRequestLine());
                    }
                    if (!request.ContainsHeader(AUTH.WwwAuthResp))
                    {
                        if (this.log.IsDebugEnabled())
                        {
                            this.log.Debug("Target auth state: " + targetAuthState.GetState());
                        }
                        this.authenticator.GenerateAuthResponse(request, targetAuthState, context);
                    }
                    if (!request.ContainsHeader(AUTH.ProxyAuthResp) && !route.IsTunnelled())
                    {
                        if (this.log.IsDebugEnabled())
                        {
                            this.log.Debug("Proxy auth state: " + proxyAuthState.GetState());
                        }
                        this.authenticator.GenerateAuthResponse(request, proxyAuthState, context);
                    }
                    response = requestExecutor.Execute(request, managedConn, context);
                    // The connection is in or can be brought to a re-usable state.
                    if (reuseStrategy.KeepAlive(response, context))
                    {
                        // Set the idle duration of this connection
                        long duration = keepAliveStrategy.GetKeepAliveDuration(response, context);
                        if (this.log.IsDebugEnabled())
                        {
                            string s;
                            if (duration > 0)
                            {
                                s = "for " + duration + " " + TimeUnit.Milliseconds;
                            }
                            else
                            {
                                s = "indefinitely";
                            }
                            this.log.Debug("Connection can be kept alive " + s);
                        }
                        connHolder.SetValidFor(duration, TimeUnit.Milliseconds);
                        connHolder.MarkReusable();
                    }
                    else
                    {
                        connHolder.MarkNonReusable();
                    }
                    if (NeedAuthentication(targetAuthState, proxyAuthState, route, response, context))
                    {
                        // Make sure the response body is fully consumed, if present
                        HttpEntity entity = response.GetEntity();
                        if (connHolder.IsReusable())
                        {
                            EntityUtils.Consume(entity);
                        }
                        else
                        {
                            managedConn.Close();
                            if (proxyAuthState.GetState() == AuthProtocolState.Success && proxyAuthState.GetAuthScheme
                                    () != null && proxyAuthState.GetAuthScheme().IsConnectionBased())
                            {
                                this.log.Debug("Resetting proxy auth state");
                                proxyAuthState.Reset();
                            }
                            if (targetAuthState.GetState() == AuthProtocolState.Success && targetAuthState.GetAuthScheme
                                    () != null && targetAuthState.GetAuthScheme().IsConnectionBased())
                            {
                                this.log.Debug("Resetting target auth state");
                                targetAuthState.Reset();
                            }
                        }
                        // discard previous auth headers
                        IHttpRequest original = request.GetOriginal();
                        if (!original.ContainsHeader(AUTH.WwwAuthResp))
                        {
                            request.RemoveHeaders(AUTH.WwwAuthResp);
                        }
                        if (!original.ContainsHeader(AUTH.ProxyAuthResp))
                        {
                            request.RemoveHeaders(AUTH.ProxyAuthResp);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                if (userToken == null)
                {
                    userToken = userTokenHandler.GetUserToken(context);
                    context.SetAttribute(HttpClientContext.UserToken, userToken);
                }
                if (userToken != null)
                {
                    connHolder.SetState(userToken);
                }
                // check for entity, release connection if possible
                HttpEntity entity_1 = response.GetEntity();
                if (entity_1 == null || !entity_1.IsStreaming())
                {
                    // connection not needed and (assumed to be) in re-usable state
                    connHolder.ReleaseConnection();
                    return(Proxies.EnhanceResponse(response, null));
                }
                else
                {
                    return(Proxies.EnhanceResponse(response, connHolder));
                }
            }
            catch (ConnectionShutdownException ex)
            {
                ThreadInterruptedException ioex = new ThreadInterruptedException("Connection has been shut down"
                                                                                 );
                Sharpen.Extensions.InitCause(ioex, ex);
                throw ioex;
            }
            catch (HttpException ex)
            {
                connHolder.AbortConnection();
                throw;
            }
            catch (IOException ex)
            {
                connHolder.AbortConnection();
                throw;
            }
            catch (RuntimeException ex)
            {
                connHolder.AbortConnection();
                throw;
            }
        }