org.apache.http.impl.client.DefaultRedirectStrategy Java Examples

The following examples show how to use org.apache.http.impl.client.DefaultRedirectStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestEntityRestStorageService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public RequestEntityRestStorageService(final S3Session session, final HttpClientBuilder configuration) {
    super(null, new PreferencesUseragentProvider().get(), null, toProperties(session.getHost(), session.getSignatureVersion()));
    this.session = session;
    this.properties = this.getJetS3tProperties();
    // Client configuration
    configuration.disableContentCompression();
    configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
    configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if(response.containsHeader("x-amz-bucket-region")) {
                final String host = ((HttpUriRequest) request).getURI().getHost();
                if(!StringUtils.equals(session.getHost().getHostname(), host)) {
                    regionEndpointCache.putRegionForBucketName(
                        StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0],
                        response.getFirstHeader("x-amz-bucket-region").getValue());
                }
            }
            return super.getRedirect(request, response, context);
        }
    });
    this.setHttpClient(configuration.build());
}
 
Example #2
Source File: HttpProxyClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private HttpAsyncClientBuilder setRedirects(HttpAsyncClientBuilder clientBuilder) {
  clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
    /** Redirectable methods. */
    private String[] REDIRECT_METHODS = new String[] { 
      HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, 
      HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
      for (String m : REDIRECT_METHODS) {
        if (m.equalsIgnoreCase(method)) {
          return true;
        }
      }
      return false;
    }
  });
  return clientBuilder;
}
 
Example #3
Source File: HttpClientRedirectLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
    final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
        /** Redirectable methods. */
        private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};

        @Override
        protected boolean isRedirectable(final String method) {
            return Arrays.stream(REDIRECT_METHODS)
              .anyMatch(m -> m.equalsIgnoreCase(method));
        }
    }).build();

    response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example #4
Source File: ProxyFilter.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Allows you do override the HTTP Client used to execute the requests.
 * By default, it used a custom client without cookies.
 *
 * @return the HTTP Client instance
 */
protected HttpClient newHttpClient() {
    return HttpClients.custom()
            // Do not manage redirection.
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String method) {
                    return followRedirect(method);
                }
            })
            .setDefaultCookieStore(new BasicCookieStore() {
                @Override
                public synchronized List<Cookie> getCookies() {
                    return Collections.emptyList();
                }
            })
            .build();
}
 
Example #5
Source File: SaveOriginalPostRequestTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private TestHttpClient createHttpClient() {
    TestHttpClient client = new TestHttpClient();

    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });

    return client;
}
 
Example #6
Source File: MetricFetcher.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public MetricFetcher() {
    int cores = Runtime.getRuntime().availableProcessors() * 2;
    long keepAliveTime = 0;
    int queueSize = 2048;
    RejectedExecutionHandler handler = new DiscardPolicy();
    fetchService = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler);
    fetchWorker = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler);
    IOReactorConfig ioConfig = IOReactorConfig.custom()
        .setConnectTimeout(3000)
        .setSoTimeout(3000)
        .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
        .build();

    httpclient = HttpAsyncClients.custom()
        .setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            protected boolean isRedirectable(final String method) {
                return false;
            }
        }).setMaxConnTotal(4000)
        .setMaxConnPerRoute(1000)
        .setDefaultIOReactorConfig(ioConfig)
        .build();
    httpclient.start();
    start();
}
 
Example #7
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public SentinelApiClient() {
    IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000)
        .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build();
    httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(final String method) {
            return false;
        }
    }).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build();
    httpClient.start();
}
 
Example #8
Source File: MetricFetcher.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public MetricFetcher() {
    int cores = Runtime.getRuntime().availableProcessors() * 2;
    long keepAliveTime = 0;
    int queueSize = 2048;
    RejectedExecutionHandler handler = new DiscardPolicy();
    fetchService = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler);
    fetchWorker = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler);
    IOReactorConfig ioConfig = IOReactorConfig.custom()
        .setConnectTimeout(3000)
        .setSoTimeout(3000)
        .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
        .build();

    httpclient = HttpAsyncClients.custom()
        .setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            protected boolean isRedirectable(final String method) {
                return false;
            }
        }).setMaxConnTotal(4000)
        .setMaxConnPerRoute(1000)
        .setDefaultIOReactorConfig(ioConfig)
        .build();
    httpclient.start();
    start();
}
 
Example #9
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public SentinelApiClient() {
    IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000)
        .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build();
    httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(final String method) {
            return false;
        }
    }).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build();
    httpClient.start();
}
 
Example #10
Source File: WebDriverSetup.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static Container createContainer(int uiPort, File testDir) throws Exception {
    File adminFile = new File(testDir, "admin.json");
    Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
    Container container;
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(testDir, true, ImmutableList.of());
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.of());
    }
    // wait for UI to be available (UI starts asynchronously in order to not block startup)
    CloseableHttpClient httpClient = HttpClients.custom()
            .setRedirectStrategy(new DefaultRedirectStrategy())
            .build();
    Stopwatch stopwatch = Stopwatch.createStarted();
    Exception lastException = null;
    while (stopwatch.elapsed(SECONDS) < 10) {
        HttpGet request = new HttpGet("http://localhost:" + uiPort);
        try (CloseableHttpResponse response = httpClient.execute(request);
                InputStream content = response.getEntity().getContent()) {
            ByteStreams.exhaust(content);
            lastException = null;
            break;
        } catch (Exception e) {
            lastException = e;
        }
    }
    httpClient.close();
    if (lastException != null) {
        throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
    }
    return container;
}
 
Example #11
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * Gets HttpClient object
 *
 * @return HttpClient
 */
private static CloseableHttpClient getHttpClient(int timeout)
{
  RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout)
      .setConnectionRequestTimeout(timeout)
      .setSocketTimeout(timeout)
      .build();

  Registry<ConnectionSocketFactory> registry =
      RegistryBuilder.<ConnectionSocketFactory>create()
          .register("http",
                    new HttpUtil.SFConnectionSocketFactory())
          .build();

  // Build a connection manager with enough connections
  PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
  connectionManager.setMaxTotal(1);
  connectionManager.setDefaultMaxPerRoute(10);

  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
      .setDefaultRequestConfig(config)
      .setConnectionManager(connectionManager)
      // Support JVM proxy settings
      .useSystemProperties()
      .setRedirectStrategy(new DefaultRedirectStrategy())
      .disableCookieManagement();

  if (HttpUtil.useProxy)
  {
    // use the custom proxy properties
    HttpHost proxy = new HttpHost(HttpUtil.proxyHost, HttpUtil.proxyPort);
    SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner(
        HttpUtil.proxyHost, HttpUtil.proxyPort, HttpUtil.nonProxyHosts
    );
    httpClientBuilder = httpClientBuilder
        .setProxy(proxy)
        .setRoutePlanner(sdkProxyRoutePlanner);
    if (!Strings.isNullOrEmpty(HttpUtil.proxyUser) && !Strings.isNullOrEmpty(HttpUtil.proxyPassword))
    {
      Credentials credentials =
          new UsernamePasswordCredentials(HttpUtil.proxyUser, HttpUtil.proxyPassword);
      AuthScope authScope = new AuthScope(HttpUtil.proxyHost, HttpUtil.proxyPort);
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(authScope, credentials);
      httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
  }

  // using the default HTTP client
  return httpClientBuilder.build();
}