Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#disableRedirectHandling()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#disableRedirectHandling() . 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: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient getCarelessHttpClient(boolean disableRedirect) {
    CloseableHttpClient httpClient = null;

    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder httpClientBuilder = HttpClients
                .custom()
                .setSSLSocketFactory(sslsf);
        if (disableRedirect) {
            httpClientBuilder.disableRedirectHandling();
        }
        httpClientBuilder.setUserAgent("swagger-validator");
        httpClient = httpClientBuilder.build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        LOGGER.error("can't disable SSL verification", e);
    }

    return httpClient;
}
 
Example 2
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a client with all our selected properties / params.
 * 
 * @param timeout
 *            - socket timeout to set
 * @return client
 */
public static final HttpClient getClient(int timeout) {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    // set the proxy if the user has one set
    if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
        HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort")));
        client.setProxy(proxy);
    }
    return client.build();
}
 
Example 3
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a client with all our selected properties / params and SSL enabled.
 * 
 * @return client
 */
public static final HttpClient getSecureClient() {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the ssl verifier to accept all
    client.setSSLHostnameVerifier(new NoopHostnameVerifier());
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    return client.build();
}
 
Example 4
Source File: HTTPStrictTransportSecurityIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
 
Example 5
Source File: retrieve-media-for-room-recording.7.x.java    From api-snippets with MIT License 5 votes vote down vote up
public static void main(String args[]) throws IOException {
    // Disable HttpClient follow redirect by default
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.disableRedirectHandling();

    // Initialize the client
    TwilioRestClient restClient = new TwilioRestClient
            .Builder(API_KEY_SID, API_KEY_SECRET)
            .httpClient(new NetworkHttpClient(clientBuilder))
            .build();

    // Retrieve media location
    String roomSid = "RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    String recordingSid = "RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    Request request = new Request(
        HttpMethod.GET,
        Domains.VIDEO.toString(),
        "/v1/Rooms/" + roomSid +
        "/Recordings/" + recordingSid +
        "/Media/",
        restClient.getRegion()
    );
    Response response = restClient.request(request);
    JSONObject json = new JSONObject(response.getContent());
    String mediaLocation = json.getString("redirect_to");

    // Retrieve media content
    String mediaContent = org.apache.http.client.fluent.Request
            .Get(mediaLocation)
            .execute()
            .handleResponse((r) ->
                    IOUtils.toString(r.getEntity().getContent()));

    System.out.println(mediaContent);
}
 
Example 6
Source File: retrieve-recording-binary-data.7.x.java    From api-snippets with MIT License 5 votes vote down vote up
public static void main(String args[]) throws IOException {
    // Disable HttpClient follow redirect by default
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.disableRedirectHandling();

    // Initialize the client
    TwilioRestClient restClient = new TwilioRestClient
            .Builder(API_KEY_SID, API_KEY_SECRET)
            .httpClient(new NetworkHttpClient(clientBuilder))
            .build();

    // Retrieve media location
    String recordingSid = "RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    Request request = new Request(
            HttpMethod.GET,
            Domains.VIDEO.toString(),
            "/v1/Recordings/" + recordingSid + "/Media/",
            restClient.getRegion()
    );
    Response response = restClient.request(request);
    JSONObject json = new JSONObject(response.getContent());
    String mediaLocation = json.getString("redirect_to");

    // Retrieve media content
    String mediaContent = org.apache.http.client.fluent.Request
            .Get(mediaLocation)
            .execute()
            .handleResponse((r) ->
                    IOUtils.toString(r.getEntity().getContent()));

    System.out.println(mediaContent);
}
 
Example 7
Source File: ApacheHttpClient.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Create new http client using custom configuration.
 *
 * @param configuration Client configuration.
 * @param server Embedded server.
 * @return Http client.
 * @throws NullPointerException If {@code server} or {@code configuration} are {@code null}.
 */
public static ApacheHttpClient newApacheHttpClient(HttpClientConfiguration configuration, EmbeddedServer<?> server) {
	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	if (!configuration.isFollowRedirect()) {
		httpClientBuilder.disableRedirectHandling();
	}

	CloseableHttpClient client = httpClientBuilder.build();
	return new ApacheHttpClient(configuration, server, client);
}
 
Example 8
Source File: Http4FileProvider.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http4FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
 *
 * @param builder Configuration options builder for HTTP4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @return an {@link HttpClientBuilder} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientBuilder createHttpClientBuilder(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final List<Header> defaultHeaders = new ArrayList<>();
    defaultHeaders.add(new BasicHeader(HTTP.USER_AGENT, builder.getUserAgent(fileSystemOptions)));

    final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions)
            ? DefaultConnectionReuseStrategy.INSTANCE
            : NoConnectionReuseStrategy.INSTANCE;

    final HttpClientBuilder httpClientBuilder =
            HttpClients.custom()
            .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions))
            .setConnectionManager(createConnectionManager(builder, fileSystemOptions))
            .setSSLContext(createSSLContext(builder, fileSystemOptions))
            .setSSLHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions))
            .setConnectionReuseStrategy(connectionReuseStrategy)
            .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions))
            .setDefaultHeaders(defaultHeaders)
            .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));

    if (!builder.getFollowRedirect(fileSystemOptions)) {
        httpClientBuilder.disableRedirectHandling();
    }

    return httpClientBuilder;
}
 
Example 9
Source File: TCKBase.java    From smallrye-health with Apache License 2.0 4 votes vote down vote up
private Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

        StringBuilder content = new StringBuilder();
        int code;

        try {

            HttpClientBuilder builder = HttpClientBuilder.create();
            if (!followRedirects) {
                builder.disableRedirectHandling();
            }

            if (useAuth) {
                CredentialsProvider provider = new BasicCredentialsProvider();
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
                provider.setCredentials(AuthScope.ANY, credentials);
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();

            HttpResponse response = client.execute(new HttpGet(theUrl));
            code = response.getStatusLine().getStatusCode();

            if (response.getEntity() != null) {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line + "\n");
                }
                bufferedReader.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new Response(code, content.toString());
    }
 
Example 10
Source File: TCKBase.java    From microprofile-health with Apache License 2.0 4 votes vote down vote up
private Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

        StringBuilder content = new StringBuilder();
        int code;

        try {

            HttpClientBuilder builder = HttpClientBuilder.create();
            if (!followRedirects) {
                builder.disableRedirectHandling();
            }

            if (useAuth) {
                CredentialsProvider provider = new BasicCredentialsProvider();
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
                provider.setCredentials(AuthScope.ANY, credentials);
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();

            HttpResponse response = client.execute(new HttpGet(theUrl));
            code = response.getStatusLine().getStatusCode();

            if (response.getEntity() != null) {

                BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent())
                );

                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line + "\n");
                }
                bufferedReader.close();
            }

        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new Response(code, content.toString());
    }