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

The following examples show how to use org.apache.http.impl.client.LaxRedirectStrategy. 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: AbstractKeycloakIdentityProviderTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Rest template setup including a disabled SSL certificate validation.
 * @throws Exception in case of errors
 */
private static void setupRestTemplate() throws Exception {
	final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
               .loadTrustMaterial(null, acceptingTrustStrategy)
               .build();
	final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	final HttpClient httpClient = HttpClientBuilder.create()
    		.setRedirectStrategy(new LaxRedirectStrategy())
    		.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
    		.build();
	factory.setHttpClient(httpClient);
	restTemplate.setRequestFactory(factory);		

	for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
		if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
			restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
			break;
		}
	}
}
 
Example #2
Source File: GithubHttp.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
public static String getGithubZipball(String owner, String repo, String destFolder) throws IOException {
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();
    String urlForGet = "https://api.github.com/repos/" + owner + "/" + repo + "/zipball/";

    HttpGet get = new HttpGet(urlForGet);

    HttpResponse response = httpclient.execute(get);

    InputStream is = response.getEntity().getContent();
    String filePath = destFolder + File.separator + repo + ".zip";
    FileOutputStream fos = new FileOutputStream(new File(filePath));

    int inByte;
    while ((inByte = is.read()) != -1)
        fos.write(inByte);
    is.close();
    fos.close();
    return filePath;
}
 
Example #3
Source File: LegacyMmsConnection.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
protected CloseableHttpClient constructHttpClient() throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL                 mmsc          = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
 
Example #4
Source File: FaviconServlet.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    // Create a pool of HTTP connections to use to get the favicons
    client = HttpClientBuilder.create()
        .setConnectionManager(new PoolingHttpClientConnectionManager())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .build();
    // Load the default favicon to use when no favicon was found of a remote host
    try {
       defaultBytes = Files.readAllBytes(Paths.get(JiveGlobals.getHomeDirectory(), "plugins/admin/webapp/images/server_16x16.gif"));
    }
    catch (final IOException e) {
        LOGGER.warn("Unable to retrieve default favicon", e);
    }
    // Initialize caches.
    missesCache = CacheFactory.createCache("Favicon Misses");
    hitsCache = CacheFactory.createCache("Favicon Hits");
}
 
Example #5
Source File: BaseTest.java    From oxAuth with MIT License 6 votes vote down vote up
public static CloseableHttpClient createHttpClientTrustAll()
		throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
	SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			return true;
		}
	}).build();
	SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext);
	CloseableHttpClient httpclient = HttpClients.custom()
			.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
			.setSSLSocketFactory(sslContextFactory)
			.setRedirectStrategy(new LaxRedirectStrategy()).build();

	return httpclient;
}
 
Example #6
Source File: MTGDesignPicturesProvider.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private void connect() throws IOException {
	String u = BASE_URI+"/login";
	httpclient = HttpClients.custom().setUserAgent(MTGConstants.USER_AGENT).setRedirectStrategy(new LaxRedirectStrategy()).build();

	HttpEntity p = httpclient.execute(new HttpGet(u), httpContext).getEntity();
	String token = URLTools.toHtml(EntityUtils.toString(p)).select("input[name=_token]").first().attr("value");
	HttpPost login = new HttpPost(u);
	List<NameValuePair> nvps = new ArrayList<>();
						nvps.add(new BasicNameValuePair("email", getString("LOGIN")));
						nvps.add(new BasicNameValuePair("password", getString("PASS")));
						nvps.add(new BasicNameValuePair("remember", "on"));
						nvps.add(new BasicNameValuePair("_token", token));
	
	login.setEntity(new UrlEncodedFormEntity(nvps));
	login.addHeader(URLTools.REFERER, u);
	login.addHeader(URLTools.UPGR_INSECURE_REQ, "1");
	login.addHeader(URLTools.ORIGIN, BASE_URI);
	
	HttpResponse resp = httpclient.execute(login, httpContext);
	
	logger.debug("Connection : " +  resp.getStatusLine().getReasonPhrase());
	
}
 
Example #7
Source File: HttpServiceImpl.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse Get(final String uri, final List<Cookie> cookies) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpGet get = new HttpGet(uri);

    if (cookies != null) {
        for (final Cookie c : cookies) {
            client.getCookieStore().addCookie(c);
        }
    }

    final HttpResponse response = client.execute(get);

    return response;
    // TODO Return something useful maybe... like an InputStream
}
 
Example #8
Source File: BaseParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 6 votes vote down vote up
BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);
    this.debuggingDataHandler = new NoOpDebuggingDataHandler();
    this.sardine = null;

    try {
        SSLConnectionSocketFactory sslsf = getSslConnectionSocketFactory(scheduleData);

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).build())
                .setUserAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: TLSEvaluationStage.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new builder instance. Callers should avoid invoking this until/unless they have validated that TLS
 * functionality is needed.
 *
 * @throws IOException if the necessary clients could not be built, which may occur if the cluster doesn't
 *                     support TLS
 */
public Builder(String serviceName, SchedulerConfig schedulerConfig) throws IOException {
  this.serviceName = serviceName;
  this.schedulerConfig = schedulerConfig;
  this.namespace = schedulerConfig.getSecretsNamespace(serviceName);
  DcosHttpExecutor executor = new DcosHttpExecutor(new DcosHttpClientBuilder()
      .setTokenProvider(schedulerConfig.getDcosAuthTokenProvider())
      .setRedirectStrategy(new LaxRedirectStrategy() {
        protected boolean isRedirectable(String method) {
          // Also treat PUT calls as redirectable
          return method.equalsIgnoreCase(HttpPut.METHOD_NAME) || super.isRedirectable(method);
        }
      }));
  this.tlsArtifactsUpdater = new TLSArtifactsUpdater(
      serviceName, new SecretsClient(executor), new CertificateAuthorityClient(executor));
}
 
Example #10
Source File: HttpClientHelper.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    s_logger.info("Creating new HTTP connection pool and client");
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connManager.setDefaultMaxPerRoute(MAX_ALLOCATED_CONNECTIONS_PER_ROUTE);
    connManager.setMaxTotal(MAX_ALLOCATED_CONNECTIONS);
    final RequestConfig requestConfig = RequestConfig.custom()
                                                     .setCookieSpec(CookieSpecs.DEFAULT)
                                                     .setMaxRedirects(maxRedirects)
                                                     .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                                                     .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                                                     .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                                                     .build();
    return HttpClientBuilder.create()
                            .setConnectionManager(connManager)
                            .setRedirectStrategy(new LaxRedirectStrategy())
                            .setDefaultRequestConfig(requestConfig)
                            .setDefaultCookieStore(cookieStore)
                            .setRetryHandler(new StandardHttpRequestRetryHandler())
                            .build();
}
 
Example #11
Source File: DefaultHttpClientGenerator.java    From vscrawler with Apache License 2.0 6 votes vote down vote up
public static CrawlerHttpClientBuilder setDefault(CrawlerHttpClientBuilder proxyFeedBackDecorateHttpClientBuilder) {
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setSoLinger(-1).setSoReuseAddress(false)
            .setSoTimeout(ProxyConstant.SOCKETSO_TIMEOUT).setTcpNoDelay(true).build();
    proxyFeedBackDecorateHttpClientBuilder.setDefaultSocketConfig(socketConfig)
            // .setSSLSocketFactory(sslConnectionSocketFactory)
            // dungproxy0.0.6之后的版本,默认忽略https证书检查
            .setRedirectStrategy(new LaxRedirectStrategy())
            // 注意,这里使用ua生产算法自动产生ua,如果是mobile,可以使用
            // com.virjar.vscrawler.core.net.useragent.UserAgentBuilder.randomAppUserAgent()
            .setUserAgent(UserAgentBuilder.randomUserAgent())
            // 对于爬虫来说,连接池没啥卵用,直接禁止掉(因为我们可能创建大量HttpClient,每个HttpClient一个连接池,会把系统socket资源撑爆)
            // 测试开80个httpClient抓数据大概一个小时系统就会宕机
            .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
            // 现在有些网站的网络响应头部数据有非ASCII数据,httpclient默认只使用ANSI标准解析header,这可能导致带有中文的header数据无法解析
            .setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charsets.UTF_8).build());
    return proxyFeedBackDecorateHttpClientBuilder;
}
 
Example #12
Source File: HttpConnectionManager.java    From timer with Apache License 2.0 6 votes vote down vote up
/**
 * 默认是 Bsic认证机制
 *
 * @param ip
 * @param username
 * @param password
 * @return
 */
public static HttpClient getHtpClient(String ip, int port, String username, String password) {
    HttpHost proxy = new HttpHost(ip, port);
    Lookup<AuthSchemeProvider> authProviders =
            RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .build();
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (username != null && password != null) {
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    } else {
        credsProvider.setCredentials(AuthScope.ANY, null);
    }

    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
    CloseableHttpClient httpClient = HttpClients
            .custom()
            .setConnectionManager(cm)
            .setProxy(proxy)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(requestConfig)
            .setDefaultAuthSchemeRegistry(authProviders)
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    return httpClient;
}
 
Example #13
Source File: AbstractBasePhotozExampleAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
    public void beforePhotozExampleAdapterTest() throws Exception {
        DroneUtils.addWebDriver(jsDriver);
        this.deployer.deploy(RESOURCE_SERVER_ID);

        clientPage.navigateTo();
//        waitForPageToLoad();
        assertCurrentUrlStartsWith(clientPage.toString());

        testExecutor = JavascriptTestExecutorWithAuthorization.create(jsDriver, jsDriverTestRealmLoginPage);
        clientPage.setTestExecutorPlayground(testExecutor, appServerContextRootPage + "/" + RESOURCE_SERVER_ID);
        jsDriver.manage().deleteAllCookies();

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build()) {
            HttpGet request = new HttpGet(clientPage.toString() + "/unsecured/clean");
            httpClient.execute(request).close();
        } 
    }
 
Example #14
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    RequestConfig.Builder requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
            .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
    client.setDefaultRequestConfig(requestConfig.build());

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
    }

    return client;
}
 
Example #15
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Put(final String uri, final HttpEntity httpEntity, final String username,
                        final String password) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    final HttpPut put = new HttpPut(uri);
    put.setEntity(httpEntity);
    final HttpResponse response = client.execute(put);
    return response;
}
 
Example #16
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Put(final String uri, final HttpEntity httpEntity) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpPut put = new HttpPut(uri);
    put.setEntity(httpEntity);
    final HttpResponse response = client.execute(put);
    return response;
}
 
Example #17
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public List<Cookie> PostCookies(final String uri, final HttpEntity httpEntity) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpPost post = new HttpPost(uri);
    post.setEntity(httpEntity);
    client.execute(post);
    final List<Cookie> cookies = client.getCookieStore().getCookies();
    // client.getConnectionManager().shutdown();
    return cookies;
}
 
Example #18
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Delete(final String uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpDelete del = new HttpDelete(uri);
    final HttpResponse response = client.execute(del);
    return response;
}
 
Example #19
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Post(final String uri, final HttpEntity httpEntity,
                         final List<Cookie> cookies) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpPost post = new HttpPost(uri);
    post.setEntity(httpEntity);
    if (cookies != null) {
        for (final Cookie c : cookies) {
            client.getCookieStore().addCookie(c);
        }
    }
    final HttpResponse response = client.execute(post);
    return response;
}
 
Example #20
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Trace(final String uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpTrace trace = new HttpTrace(uri);
    final HttpResponse response = client.execute(trace);
    return response;
}
 
Example #21
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Options(final String uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpOptions options = new HttpOptions(uri);
    final HttpResponse response = client.execute(options);
    return response;
}
 
Example #22
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Get(final String uri, final Map<String, String> headers) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpGet get = new HttpGet(uri);

    for (final String header : headers.keySet()) {
        get.addHeader(header, headers.get(header));
    }

    final HttpResponse response = client.execute(get);

    return response;
    // TODO Return something useful maybe... like an InputStream
}
 
Example #23
Source File: VaultConfig.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
        throws GeneralSecurityException, IOException {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(
            DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

    if (isNoneEmpty(httpsProxyUser, httpsProxyPassword)) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(httpsProxyUser, httpsProxyPassword);
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (hasSslConfiguration(sslConfiguration)) {
        SSLContext sslContext = getSSLContext(sslConfiguration,
                getTrustManagers(sslConfiguration));
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setSSLContext(sslContext);
    }

    RequestConfig requestConfig = RequestConfig
            .custom()
            .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()))
            .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis()))
            .setAuthenticationEnabled(true)
            .build();

    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example #24
Source File: HttpClientHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
    final BasicCookieStore cookieStore = new BasicCookieStore();
    return HttpClientBuilder.create()
        .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
        .setRedirectStrategy(new LaxRedirectStrategy())
        .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setMaxRedirects(maxRedirects).build())
        .setDefaultCookieStore(cookieStore)
        .setRetryHandler(new StandardHttpRequestRetryHandler())
        .build();
}
 
Example #25
Source File: HttpClientRedirectLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
    final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();

    response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example #26
Source File: ConcurrentLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected CloseableHttpClient getHttpsAwareClient() {
    HttpClientBuilder builder = HttpClientBuilder.create()
          .setRedirectStrategy(new LaxRedirectStrategy());
    if (AUTH_SERVER_SSL_REQUIRED) {
        builder.setSSLHostnameVerifier((s, sslSession) -> true);
    }
    return builder.build();
}
 
Example #27
Source File: RobotServerService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private static void getIPOfNode(TestCaseExecution tCExecution) {
    try {
        Session session = tCExecution.getSession();
        HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();
        SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);

        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

        URL sessionURL = new URL(RobotServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);

        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        if (!response.getStatusLine().toString().contains("403")
                && !response.getEntity().getContentType().getValue().contains("text/html")) {
            InputStream contents = response.getEntity().getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(contents, writer, "UTF8");
            JSONObject object = new JSONObject(writer.toString());
            if (object.has("proxyId")) {
                URL myURL = new URL(object.getString("proxyId"));
                if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                    tCExecution.setRobotHost(myURL.getHost());
                    tCExecution.setRobotPort(String.valueOf(myURL.getPort()));
                }
            } else {
                LOG.debug("'proxyId' json data not available from remote Selenium Server request : " + writer.toString());
            }
        }

    } catch (IOException | JSONException ex) {
        LOG.error(ex.toString(), ex);
    }
}
 
Example #28
Source File: TVersionRetriever.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
private void check() {
    try {
        HttpUriRequest request = RequestBuilder
                .get()
                .setUri("http://th.tcpr.ca/thermos/version")
                .addParameter("version", Thermos.getCurrentVersion()).build();
        HttpResponse response = HttpClientBuilder.create()
                .setUserAgent("Thermos Version Retriever")
                .setRedirectStrategy(new LaxRedirectStrategy()).build()
                .execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            uncaughtException(mThread, new IllegalStateException(
                    "Status code isn't OK"));
            return;
        }
        JSONObject json = (JSONObject) sParser.parse(new InputStreamReader(
                response.getEntity().getContent()));
        String version = (String) json.get("version");
        if (!mUpToDateSupport || Thermos.getCurrentVersion() == null
                || !version.equals(Thermos.getCurrentVersion())) {
            mCallback.newVersion(version);
        } else {
            mCallback.upToDate();
        }
    } catch (Exception e) {
        uncaughtException(null, e);
    }
}
 
Example #29
Source File: ReportStatusServiceHttpImpl.java    From mantis with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient buildCloseableHttpClient() {
    return HttpClients
            .custom()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .disableAutomaticRetries()
            .setDefaultRequestConfig(
                    RequestConfig
                            .custom()
                            .setConnectTimeout(defaultConnTimeout)
                            .setConnectionRequestTimeout(defaultConnMgrTimeout)
                            .setSocketTimeout(defaultSocketTimeout)
                            .build())
            .build();
}
 
Example #30
Source File: HttpConnectionManager.java    From timer with Apache License 2.0 5 votes vote down vote up
public static HttpClient getHtpClient() {

        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient httpClient = HttpClients
                .custom()
                .setConnectionManager(cm)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpClient;
    }