Beispiel #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public String call() throws java.io.IOException
            public override string call()
            {
                HttpPost request = new HttpPost(outerInstance.APP_BASE_PATH + FETCH_AND_LOCK_PATH);

                request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                StringEntity stringEntity = new StringEntity("{ \"workerId\": \"aWorkerId\", \"asyncResponseTimeout\": 1000 }");

                request.Entity = stringEntity;

                CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
                string responseBody            = null;

                try
                {
                    HttpEntity entity = response.Entity;
                    responseBody = EntityUtils.ToString(entity);
                    request.releaseConnection();
                }
                finally
                {
                    response.close();
                }

                return(responseBody);
            }
Beispiel #2
0
        /// <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");
            CloseableHttpResponse @out = null;

            try
            {
                @out = this.requestExecutor.Execute(route, request, context, execAware);
            }
            catch (Exception ex)
            {
                if (@out != null)
                {
                    @out.Close();
                }
                if (this.connectionBackoffStrategy.ShouldBackoff(ex))
                {
                    this.backoffManager.BackOff(route);
                }
                if (ex is RuntimeException)
                {
                    throw (RuntimeException)ex;
                }
                if (ex is HttpException)
                {
                    throw (HttpException)ex;
                }
                if (ex is IOException)
                {
                    throw (IOException)ex;
                }
                throw new UndeclaredThrowableException(ex);
            }
            if (this.connectionBackoffStrategy.ShouldBackoff(@out))
            {
                this.backoffManager.BackOff(route);
            }
            else
            {
                this.backoffManager.Probe(route);
            }
            return(@out);
        }
Beispiel #3
0
 /// <summary>Unconditionally close a response.</summary>
 /// <remarks>
 /// Unconditionally close a response.
 /// <p>
 /// Example Code:
 /// <pre>
 /// HttpResponse httpResponse = null;
 /// try {
 /// httpResponse = httpClient.execute(httpGet);
 /// } catch (Exception e) {
 /// // error handling
 /// } finally {
 /// HttpClientUtils.closeQuietly(httpResponse);
 /// }
 /// </pre>
 /// </remarks>
 /// <param name="response">
 /// the HttpResponse to release resources, may be null or already
 /// closed.
 /// </param>
 /// <since>4.3</since>
 public static void CloseQuietly(CloseableHttpResponse response)
 {
     if (response != null)
     {
         try
         {
             try
             {
                 EntityUtils.Consume(response.GetEntity());
             }
             finally
             {
                 response.Close();
             }
         }
         catch (IOException)
         {
         }
     }
 }
 /// <exception cref="System.IO.IOException"></exception>
 /// <exception cref="Apache.Http.HttpException"></exception>
 public virtual CloseableHttpResponse Execute(HttpRoute route, HttpRequestWrapper
                                              request, HttpClientContext context, HttpExecutionAware execAware)
 {
     for (int c = 1; ; c++)
     {
         CloseableHttpResponse response = this.requestExecutor.Execute(route, request, context
                                                                       , execAware);
         try
         {
             if (this.retryStrategy.RetryRequest(response, c, context))
             {
                 response.Close();
                 long nextInterval = this.retryStrategy.GetRetryInterval();
                 if (nextInterval > 0)
                 {
                     try
                     {
                         this.log.Trace("Wait for " + nextInterval);
                         Sharpen.Thread.Sleep(nextInterval);
                     }
                     catch (Exception)
                     {
                         Sharpen.Thread.CurrentThread().Interrupt();
                         throw new ThreadInterruptedException();
                     }
                 }
             }
             else
             {
                 return(response);
             }
         }
         catch (RuntimeException ex)
         {
             response.Close();
             throw;
         }
     }
 }
Beispiel #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRespondToHttpClientGet() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRespondToHttpClientGet()
        {
            using (DefaultHttpClient httpclient = new DefaultHttpClient())
            {
                HttpGet httpget = new HttpGet(_serverUrl + "/?id=storeId+v=kernelVersion");
                using (CloseableHttpResponse response = httpclient.execute(httpget))
                {
                    HttpEntity entity = response.Entity;
                    if (entity != null)
                    {
                        using (Stream instream = entity.Content)
                        {
                            sbyte[] tmp = new sbyte[2048];
                            while ((instream.Read(tmp, 0, tmp.Length)) != -1)
                            {
                            }
                        }
                    }
                    assertThat(response, notNullValue());
                    assertThat(response.StatusLine.StatusCode, @is(HttpStatus.SC_OK));
                }
            }
        }
Beispiel #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void evaluatePostRequest(org.apache.http.HttpEntity reqBody, String reqContentType, int expectedStatusCode, boolean assertResponseBody) throws java.io.IOException
        private void evaluatePostRequest(HttpEntity reqBody, string reqContentType, int expectedStatusCode, bool assertResponseBody)
        {
            HttpPost post = new HttpPost(BASE_URL + START_PROCESS_INSTANCE_BY_KEY_URL);

            post.Config = reqConfig;

            if (!string.ReferenceEquals(reqContentType, null))
            {
                post.setHeader(HttpHeaders.CONTENT_TYPE, reqContentType);
            }

            post.Entity = reqBody;

            CloseableHttpResponse response = client.execute(post);

            assertEquals(expectedStatusCode, response.StatusLine.StatusCode);

            if (assertResponseBody)
            {
                assertThat(EntityUtils.ToString(response.Entity, "UTF-8"), containsString(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID));
            }

            response.close();
        }
Beispiel #7
0
        /// <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");
            IHttpRequest original = request.GetOriginal();
            URI          uri      = null;

            if (original is IHttpUriRequest)
            {
                uri = ((IHttpUriRequest)original).GetURI();
            }
            else
            {
                string uriString = original.GetRequestLine().GetUri();
                try
                {
                    uri = URI.Create(uriString);
                }
                catch (ArgumentException ex)
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Unable to parse '" + uriString + "' as a valid URI; " + "request URI and Host header may be inconsistent"
                                       , ex);
                    }
                }
            }
            request.SetURI(uri);
            // Re-write request URI if needed
            RewriteRequestURI(request, route);
            HttpParams @params     = request.GetParams();
            HttpHost   virtualHost = (HttpHost)@params.GetParameter(ClientPNames.VirtualHost);

            // HTTPCLIENT-1092 - add the port if necessary
            if (virtualHost != null && virtualHost.GetPort() == -1)
            {
                int port = route.GetTargetHost().GetPort();
                if (port != -1)
                {
                    virtualHost = new HttpHost(virtualHost.GetHostName(), port, virtualHost.GetSchemeName
                                                   ());
                }
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Using virtual host" + virtualHost);
                }
            }
            HttpHost target = null;

            if (virtualHost != null)
            {
                target = virtualHost;
            }
            else
            {
                if (uri != null && uri.IsAbsolute() && uri.GetHost() != null)
                {
                    target = new HttpHost(uri.GetHost(), uri.GetPort(), uri.GetScheme());
                }
            }
            if (target == null)
            {
                target = route.GetTargetHost();
            }
            // Get user info from the URI
            if (uri != null)
            {
                string userinfo = uri.GetUserInfo();
                if (userinfo != null)
                {
                    CredentialsProvider credsProvider = context.GetCredentialsProvider();
                    if (credsProvider == null)
                    {
                        credsProvider = new BasicCredentialsProvider();
                        context.SetCredentialsProvider(credsProvider);
                    }
                    credsProvider.SetCredentials(new AuthScope(target), new UsernamePasswordCredentials
                                                     (userinfo));
                }
            }
            // Run request protocol interceptors
            context.SetAttribute(HttpClientContext.HttpTargetHost, target);
            context.SetAttribute(HttpClientContext.HttpRoute, route);
            context.SetAttribute(HttpClientContext.HttpRequest, request);
            this.httpProcessor.Process(request, context);
            CloseableHttpResponse response = this.requestExecutor.Execute(route, request, context
                                                                          , execAware);

            try
            {
                // Run response protocol interceptors
                context.SetAttribute(HttpClientContext.HttpResponse, response);
                this.httpProcessor.Process(response, context);
                return(response);
            }
            catch (RuntimeException ex)
            {
                response.Close();
                throw;
            }
            catch (IOException ex)
            {
                response.Close();
                throw;
            }
            catch (HttpException ex)
            {
                response.Close();
                throw;
            }
        }
Beispiel #8
0
        /// <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");
            IList <URI> redirectLocations = context.GetRedirectLocations();

            if (redirectLocations != null)
            {
                redirectLocations.Clear();
            }
            RequestConfig      config         = context.GetRequestConfig();
            int                maxRedirects   = config.GetMaxRedirects() > 0 ? config.GetMaxRedirects() : 50;
            HttpRoute          currentRoute   = route;
            HttpRequestWrapper currentRequest = request;

            for (int redirectCount = 0; ;)
            {
                CloseableHttpResponse response = requestExecutor.Execute(currentRoute, currentRequest
                                                                         , context, execAware);
                try
                {
                    if (config.IsRedirectsEnabled() && this.redirectStrategy.IsRedirected(currentRequest
                                                                                          , response, context))
                    {
                        if (redirectCount >= maxRedirects)
                        {
                            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
                        }
                        redirectCount++;
                        IHttpRequest redirect = this.redirectStrategy.GetRedirect(currentRequest, response
                                                                                  , context);
                        if (!redirect.HeaderIterator().HasNext())
                        {
                            IHttpRequest original = request.GetOriginal();
                            redirect.SetHeaders(original.GetAllHeaders());
                        }
                        currentRequest = HttpRequestWrapper.Wrap(redirect);
                        if (currentRequest is HttpEntityEnclosingRequest)
                        {
                            Proxies.EnhanceEntity((HttpEntityEnclosingRequest)currentRequest);
                        }
                        URI      uri       = currentRequest.GetURI();
                        HttpHost newTarget = URIUtils.ExtractHost(uri);
                        if (newTarget == null)
                        {
                            throw new ProtocolException("Redirect URI does not specify a valid host name: " +
                                                        uri);
                        }
                        // Reset virtual host and auth states if redirecting to another host
                        if (!currentRoute.GetTargetHost().Equals(newTarget))
                        {
                            AuthState targetAuthState = context.GetTargetAuthState();
                            if (targetAuthState != null)
                            {
                                this.log.Debug("Resetting target auth state");
                                targetAuthState.Reset();
                            }
                            AuthState proxyAuthState = context.GetProxyAuthState();
                            if (proxyAuthState != null)
                            {
                                AuthScheme authScheme = proxyAuthState.GetAuthScheme();
                                if (authScheme != null && authScheme.IsConnectionBased())
                                {
                                    this.log.Debug("Resetting proxy auth state");
                                    proxyAuthState.Reset();
                                }
                            }
                        }
                        currentRoute = this.routePlanner.DetermineRoute(newTarget, currentRequest, context
                                                                        );
                        if (this.log.IsDebugEnabled())
                        {
                            this.log.Debug("Redirecting to '" + uri + "' via " + currentRoute);
                        }
                        EntityUtils.Consume(response.GetEntity());
                        response.Close();
                    }
                    else
                    {
                        return(response);
                    }
                }
                catch (RuntimeException ex)
                {
                    response.Close();
                    throw;
                }
                catch (IOException ex)
                {
                    response.Close();
                    throw;
                }
                catch (HttpException ex)
                {
                    // Protocol exception related to a direct.
                    // The underlying connection may still be salvaged.
                    try
                    {
                        EntityUtils.Consume(response.GetEntity());
                    }
                    catch (IOException ioex)
                    {
                        this.log.Debug("I/O error while releasing connection", ioex);
                    }
                    finally
                    {
                        response.Close();
                    }
                    throw;
                }
            }
        }