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; }
/** * Returns a new HTTP client by the specified repository configuration. * * @return a new HTTP client by the specified repository configuration */ private HttpClient createHttpClient() { RequestConfig.Builder requestBuilder = RequestConfig.custom().setSocketTimeout(10 * 1000); if (repoConfig.getProxy() != null) { requestBuilder.setProxy(HttpHost.create(repoConfig.getProxy())); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()); httpClientBuilder = httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)); httpClientBuilder = httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy()); if (repoConfig.getUsername() != null) { final Credentials creds = new UsernamePasswordCredentials(repoConfig.getUsername(), repoConfig.getPassword()); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } return httpClientBuilder.build(); }
private static HTTPResponse _invoke(URL url,HttpUriRequest request,String username,String password, long timeout, boolean redirect, String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers, Map<String,String> formfields) throws IOException { HttpClientBuilder builder = HttpClients.custom(); // redirect if(redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); HttpHost hh=new HttpHost(url.getHost(),url.getPort()); setHeader(request,headers); if(CollectionUtil.isEmpty(formfields))setContentType(request,charset); setFormFields(request,formfields,charset); setUserAgent(request,useragent); if(timeout>0)Http41.setTimeout(builder,TimeSpanImpl.fromMillis(timeout)); HttpContext context=setCredentials(builder,hh, username, password,false); setProxy(builder,request,proxy); CloseableHttpClient client = builder.build(); if(context==null)context = new BasicHttpContext(); return new HTTPResponse4Impl(url,context,request,client.execute(request,context)); }
@Override protected Client newClient() { ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); ResteasyClient client = resteasyClientBuilder.establishConnectionTimeout(getTimeout(), TimeUnit.MILLISECONDS).socketTimeout(getTimeout(), TimeUnit.MILLISECONDS).build(); AbstractHttpClient httpClient = (AbstractHttpClient) ((ApacheHttpClient4Engine) client.httpEngine()).getHttpClient(); httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String method) { return true; } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { request.setParams(new AllowRedirectHttpParams(request.getParams())); } }); return client; }
/** * HTTP GET Without Handling HTTP redirects automatically * * @param url * @param headers * @return CloseableHttpResponse */ public static CloseableHttpResponse getWithoutAutoRedirect(String url, Map<String, String> headers) { if (url == null) { return null; } HttpGet get = new HttpGet(url); addHeaders(get, headers); CloseableHttpResponse response = null; try { client = HttpClients.custom().disableRedirectHandling().build(); response = visit(get); RedirectStrategy rs = DefaultRedirectStrategy.INSTANCE; client = HttpClients.custom().setRedirectStrategy(rs).build(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return response; }
private static HTTPResponse _invoke(URL url,HttpUriRequest request,String username,String password, long timeout, boolean redirect, String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers, Map<String,String> formfields) throws IOException { HttpClientBuilder builder = getHttpClientBuilder(); // redirect if(redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); HttpHost hh=new HttpHost(url.getHost(),url.getPort()); setHeader(request,headers); if(CollectionUtil.isEmpty(formfields))setContentType(request,charset); setFormFields(request,formfields,charset); setUserAgent(request,useragent); if(timeout>0)Http.setTimeout(builder,TimeSpanImpl.fromMillis(timeout)); HttpContext context=setCredentials(builder,hh, username, password,false); setProxy(builder,request,proxy); CloseableHttpClient client = builder.build(); if(context==null)context = new BasicHttpContext(); return new HTTPResponse4Impl(url,context,request,client.execute(request,context)); }
private static HttpClient buildClient(final String fedoraUsername, final String fedoraPassword, final String repositoryURL) { final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager(); connMann.setMaxTotal(MAX_VALUE); connMann.setDefaultMaxPerRoute(MAX_VALUE); final DefaultHttpClient httpClient = new DefaultHttpClient(connMann); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false)); // If the Fedora instance requires authentication, set it up here if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) { LOGGER.debug("Adding BASIC credentials to client for repo requests."); final URI fedoraUri = URI.create(repositoryURL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()), new UsernamePasswordCredentials(fedoraUsername, fedoraPassword)); httpClient.setCredentialsProvider(credsProvider); } return httpClient; }
/** * 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(); }
public RequestEntityRestStorageService(final S3Session session, final Jets3tProperties properties, final HttpClientBuilder configuration) { super(session.getHost().getCredentials().isAnonymousLogin() ? null : new AWSCredentials(null, null) { @Override public String getAccessKey() { return session.getHost().getCredentials().getUsername(); } @Override public String getSecretKey() { return session.getHost().getCredentials().getPassword(); } }, new PreferencesUseragentProvider().get(), null, properties); this.session = session; 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()); }
/** * When using this constructor tracer should be registered via * {@link GlobalTracer#register(Tracer)}. */ public TracingHttpClientBuilder() { this(DefaultRedirectStrategy.INSTANCE, false, GlobalTracer.get(), Collections.<ApacheClientSpanDecorator>singletonList(new ApacheClientSpanDecorator.StandardTags())); }
@Before public void setUp() throws Exception { super.setUp(); this.clientBuilder = new TracingHttpClientBuilder(DefaultRedirectStrategy.INSTANCE, false, mockTracer, Collections.<ApacheClientSpanDecorator>singletonList(new ApacheClientSpanDecorator.StandardTags())); this.serverBootstrap.registerHandler(RedirectHandler.MAPPING, new RedirectHandler()) .registerHandler(PropagationHandler.MAPPING, new PropagationHandler()); this.serverHost = super.start(); }
@Test public void testDisableRedirectHandling() throws URISyntaxException, IOException { { HttpClient client = new TracingHttpClientBuilder(DefaultRedirectStrategy.INSTANCE, true, mockTracer, Collections.<ApacheClientSpanDecorator>singletonList(new ApacheClientSpanDecorator.StandardTags())) .build(); client.execute(new HttpGet(serverUrl(RedirectHandler.MAPPING))); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(2, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(serverUrl("/redirect"), mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(301, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals(serverHost.getPort(), mockSpan.tags().get(Tags.PEER_PORT.getKey())); Assert.assertEquals(serverHost.getHostName(), mockSpan.tags().get(Tags.PEER_HOSTNAME.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); assertLocalSpan(mockSpans.get(1)); }
private static Container createContainer(int uiPort, File testDir) throws Exception { File adminFile = new File(testDir, "admin.json"); Files.asCharSink(adminFile, Charsets.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; }
public HttpClientBuilder buildHttpClient() { final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final List<Header> headers = Lists.newArrayList(new BasicHeader("Accept", "*/*"),new BasicHeader("User-Agent", USER_AGENT)); httpClientBuilder.setDefaultHeaders(headers); httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy()); return httpClientBuilder; }
public static DefaultHttpClient getHttpClient() { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5*1000); client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false)); client.setRedirectStrategy(new DefaultRedirectStrategy()); return client; }
private void executeCheck(Application app) { Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName()); try { logCurrent.info("executeCheck for: " + app.getPath()); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient = (DefaultHttpClient) ClientSSLResistanceExtender.wrapClient(httpClient); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); String strNSFURL = app.getPath(); String strRedirection = strNSFURL + "/xsp/xpage.agent?action=check"; HttpGet getRequestINIT = new HttpGet(strNSFURL); HttpGet getRequest = new HttpGet(strRedirection); getRequest.addHeader(BasicScheme.authenticate(app.getCredentias(), "UTF-8", false)); getRequestINIT.addHeader(BasicScheme.authenticate(app.getCredentias(), "UTF-8", false)); HttpResponse hsrINTI = httpClient.execute(getRequestINIT); app.setLastStatus(hsrINTI.getStatusLine().getStatusCode()); app.setLastReason(hsrINTI.getStatusLine().getReasonPhrase()); app.setLastTry(new Date()); if (hsrINTI.getStatusLine().getStatusCode() == 200) { EntityUtils.consume(hsrINTI.getEntity()); HttpResponse hsr = httpClient.execute(getRequest); logCurrent.fine("Result from executeCheck: " + EntityUtils.toString(hsr.getEntity())); } else { EntityUtils.consume(hsrINTI.getEntity()); logCurrent.severe(app.getPath() + " does not response! -> " + hsrINTI.getStatusLine().toString()); } logCurrent.info("executeCheck done"); } catch (Exception e) { e.printStackTrace(); } }
private void handleRedirects(RESTPool pool, HttpAsyncClientBuilder builder) { if (pool.followRedirects()) builder.setRedirectStrategy(DefaultRedirectStrategy.INSTANCE); }
/** * Build an Http client using our set of default. * * @return HttpClient object */ private static HttpClient buildHttpClient() { // set timeout so that we don't wait forever. // Setup the default configuration for all requests on this client DefaultRequestConfig = RequestConfig.custom() .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT) .setSocketTimeout(DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT) .build(); // enforce using tlsv1.2 SSLContext sslContext = SSLContexts.createDefault(); // cipher suites need to be picked up in code explicitly for jdk 1.7 // https://stackoverflow.com/questions/44378970/ String[] cipherSuites = decideCipherSuites(); if (logger.isTraceEnabled()) { logger.trace("Cipher suites used: {}", Arrays.toString(cipherSuites)); } SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext, new String[] {"TLSv1.2"}, cipherSuites, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); // Build a connection manager with enough connections connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(DefaultRequestConfig) .setConnectionManager(connectionManager) // Support JVM proxy settings .useSystemProperties() .setRedirectStrategy(new DefaultRedirectStrategy()) .setUserAgent("-") // needed for Okta .build(); return httpClient; }
public ExecutionUserProperties checkPassword(String strUser, String strPW, String strURL) { ExecutionUserProperties eupRC = new ExecutionUserProperties(); eupRC.setLoggedIn(false); try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient = (DefaultHttpClient) ClientSSLResistanceExtender.wrapClient(httpClient); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); /* * String strNSFURL = strURL; String strRedirection = strNSFURL + * "/xsp/xpage.agent?loginCheck"; java.util.List<NameValuePair> * formparams = new ArrayList<NameValuePair>(); formparams.add(new * BasicNameValuePair("username", strUser)); formparams.add(new * BasicNameValuePair("password", strPW)); formparams.add(new * BasicNameValuePair("redirectto", strRedirection)); * UrlEncodedFormEntity entity = new * UrlEncodedFormEntity(formparams, "UTF-8"); * * HttpPost postRequest = new HttpPost(strNSFURL + "?login"); * postRequest.getParams().setParameter(ClientPNames.COOKIE_POLICY, * org * .apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY); * * postRequest.setHeader("Content-Type", * "application/x-www-form-urlencoded"); * postRequest.addHeader("accept", "application/json"); * postRequest.setEntity(entity); HttpResponse hsr = * httpClient.execute(postRequest); for (Cookie ck : * httpClient.getCookieStore().getCookies()) { if * ("LtpaToken".equalsIgnoreCase(ck.getName())) { blRC = true; } if * ("DomAuthSessId".equalsIgnoreCase(ck.getName())) { blRC = true; } * } */ String strNSFURL = strURL; String strRedirection = strNSFURL + "/xsp/xpage.agent?action=checkLogin"; HttpGet getRequestINIT = new HttpGet(strNSFURL); HttpGet getRequest = new HttpGet(strRedirection); getRequest.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(strUser, strPW), "UTF-8", false)); getRequestINIT.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(strUser, strPW), "UTF-8", false)); HttpResponse hsrINTI = httpClient.execute(getRequestINIT); if (hsrINTI.getStatusLine().getStatusCode() == 200) { EntityUtils.consume(hsrINTI.getEntity()); HttpResponse hsr = httpClient.execute(getRequest); JsonJavaObject json = (JsonJavaObject) JsonParser.fromJson(JsonJavaFactory.instanceEx, EntityUtils.toString(hsr.getEntity())); if (json.getString("status").equalsIgnoreCase("ok")) { eupRC.setLoggedIn(true); eupRC.setUserName(json.getString("username")); eupRC.setAccessLevel(json.getInt("level")); } else { eupRC.setLoggedIn(false); } } } catch (Exception e) { e.printStackTrace(); } return eupRC; }
/** * Return all redirected URLs. * * @param builder Http client builder * @param source Source URI * @return a list of redirected URLs * @throws IOException */ public static List<URI> getRedirected( final HttpClientBuilder builder , final URI source ) throws IOException { if ( builder == null || source == null ) { throw new IllegalArgumentException(); } final List<URI> uris = new ArrayList<>(); builder.setRedirectStrategy( new DefaultRedirectStrategy() { @Override public HttpUriRequest getRedirect( final HttpRequest request , final HttpResponse response , final HttpContext context ) throws ProtocolException { final HttpUriRequest r = super.getRedirect( request , response , context ); uris.add( r.getURI() ); return r; } } ) .build(); try( final CloseableHttpClient client = builder.build() ) { final HttpGet get = new HttpGet( source ); client.execute( get ); get.abort(); } return uris; }