List of usage examples for org.apache.http.impl.client DefaultHttpClient setRedirectStrategy
public synchronized void setRedirectStrategy(final RedirectStrategy strategy)
From source file:drmaas.sandbox.http.LoginTest.java
public static void main(String[] args) throws Exception { //1. For SSL/*w w w.j av a 2s. c om*/ DefaultHttpClient base = new DefaultHttpClient(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; X509HostnameVerifier verifier = new X509HostnameVerifier() { @Override public void verify(String string, SSLSocket ssls) throws IOException { } @Override public void verify(String string, X509Certificate xc) throws SSLException { } @Override public void verify(String string, String[] strings, String[] strings1) throws SSLException { } @Override public boolean verify(String string, SSLSession ssls) { return true; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, base.getParams()); httpclient.setRedirectStrategy(new LaxRedirectStrategy()); try { HttpPost httpost; HttpResponse response; HttpEntity entity; List<Cookie> cookies; BufferedReader rd; String line; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); //log in httpost = new HttpPost("myloginurl"); nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("login", "Log In")); nvps.add(new BasicNameValuePair("os_username", "foo")); nvps.add(new BasicNameValuePair("os_password", "foobar")); nvps.add(new BasicNameValuePair("os_cookie", "true")); nvps.add(new BasicNameValuePair("os_destination", "")); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = httpclient.execute(httpost); System.out.println(response.toString()); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.uiautomation.ios.communication.HttpClientFactory.java
public static DefaultHttpClient getClient() { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new MyRedirectHandler()); return client; }
From source file:org.commonjava.redhat.maven.rv.util.InputUtils.java
public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting) throws ValidationException { if (client == null) { final DefaultHttpClient hc = new DefaultHttpClient(); hc.setRedirectStrategy(new DefaultRedirectStrategy()); final String proxyHost = System.getProperty("http.proxyHost"); final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1")); if (proxyHost != null && proxyPort > 0) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); }/*from ww w . j a va 2 s. c om*/ client = hc; } File result = null; if (location.startsWith("http")) { LOGGER.info("Downloading: '" + location + "'..."); try { final URL url = new URL(location); final String userpass = url.getUserInfo(); if (!isEmpty(userpass)) { final AuthScope scope = new AuthScope(url.getHost(), url.getPort()); final Credentials creds = new UsernamePasswordCredentials(userpass); client.getCredentialsProvider().setCredentials(scope, creds); } } catch (final MalformedURLException e) { LOGGER.error("Malformed URL: '" + location + "'", e); throw new ValidationException("Failed to download: %s. Reason: %s", e, location, e.getMessage()); } final File downloaded = new File(downloadsDir, new File(location).getName()); if (deleteExisting && downloaded.exists()) { downloaded.delete(); } if (!downloaded.exists()) { HttpGet get = new HttpGet(location); OutputStream out = null; try { HttpResponse response = client.execute(get); // Work around for scenario where we are loading from a server // that does a refresh e.g. gitweb if (response.containsHeader("Cache-control")) { LOGGER.info("Waiting for server to generate cache..."); try { Thread.sleep(5000); } catch (final InterruptedException e) { } get.abort(); get = new HttpGet(location); response = client.execute(get); } final int code = response.getStatusLine().getStatusCode(); if (code == 200) { final InputStream in = response.getEntity().getContent(); out = new FileOutputStream(downloaded); copy(in, out); } else { LOGGER.info(String.format("Received status: '%s' while downloading: %s", response.getStatusLine(), location)); throw new ValidationException("Received status: '%s' while downloading: %s", response.getStatusLine(), location); } } catch (final ClientProtocolException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } catch (final IOException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } finally { closeQuietly(out); get.abort(); } } result = downloaded; } else { LOGGER.info("Using local file: '" + location + "'..."); result = new File(location); } return result; }
From source file:com.redhat.rcm.version.util.InputUtils.java
private static void setupClient() throws VManException { if (client == null) { SSLSocketFactory sslSocketFactory; try {//from www . ja va2 s . c om sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null, new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // sslSocketFactory = // new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null, // SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER ); } catch (final KeyManagementException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final UnrecoverableKeyException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final NoSuchAlgorithmException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final KeyStoreException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(); ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient hc = new DefaultHttpClient(ccm); hc.setRedirectStrategy(new DefaultRedirectStrategy()); final String proxyHost = System.getProperty("http.proxyHost"); final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1")); if (proxyHost != null && proxyPort > 0) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } client = hc; } }
From source file:org.ocpsoft.rewrite.servlet.config.SchemeChangeTest.java
@Test public void testRedirectToHttps() { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new RedirectStrategy() { @Override/*from ww w .j a va 2 s .c o m*/ public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { if (response.getFirstHeader("Location").getValue().contains("https")) throw new RuntimeException("Success!"); return false; } @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { throw new IllegalStateException("Not implemented."); } }); try { get(client, "/login"); } catch (Exception e) { if (!"Success!".equals(e.getMessage())) Assert.fail(); } }
From source file:org.openqa.selenium.remote.internal.HttpClientFactory.java
public HttpClient getGridHttpClient(int connection_timeout, int socket_timeout) { DefaultHttpClient gridClient = new DefaultHttpClient(gridClientConnectionManager); gridClient.setRedirectStrategy(new MyRedirectHandler()); gridClient.setParams(getGridHttpParams(connection_timeout, socket_timeout)); gridClient.setRoutePlanner(getRoutePlanner(gridClient.getConnectionManager().getSchemeRegistry())); gridClient.getConnectionManager().closeIdleConnections(100, TimeUnit.MILLISECONDS); return gridClient; }
From source file:juzu.impl.bridge.context.AbstractContextClientTestCase.java
protected void test(URL initialURL, String kind) throws Exception { driver.get(initialURL.toString());/*from w w w.ja v a 2 s . c o m*/ WebElement link = driver.findElement(By.id(kind)); contentLength = -1; charset = null; contentType = null; content = null; URL url = new URL(link.getAttribute("href")); DefaultHttpClient client = new DefaultHttpClient(); // Little trick to force redirect after post client.setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String method) { return true; } }); try { HttpPost post = new HttpPost(url.toURI()); post.setEntity(new StringEntity("foo", ContentType.create("application/octet-stream", "UTF-8"))); HttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(3, contentLength); assertEquals("UTF-8", charset); assertEquals("application/octet-stream; charset=UTF-8", contentType); assertEquals("foo", content); assertEquals(kind, AbstractContextClientTestCase.kind); } finally { client.getConnectionManager().shutdown(); } }
From source file:gov.medicaid.screening.dao.impl.AccreditedBirthCentersLicenseDAOBean.java
/** * Retrieves all results from the source site. * //from w w w . j a v a 2s . co m * @return the birth centers matched * @throws URISyntaxException * if the URL could not be correctly constructed * @throws IOException * for any I/O related errors * @throws ServiceException * for any other errors encountered */ private List<AccreditedBirthCenter> getAllResults() throws URISyntaxException, IOException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy()); HttpGet getFrontPage = new HttpGet(new URIBuilder(getSearchURL()).build()); HttpResponse response = client.execute(getFrontPage); verifyAndAuditCall(getSearchURL(), response); Document page = Jsoup.parse(EntityUtils.toString(response.getEntity())); List<AccreditedBirthCenter> allCenters = new ArrayList<AccreditedBirthCenter>(); Elements rows = page.select("table#wp-table-reloaded-id-1-no-1 tbody tr"); for (Element row : rows) { AccreditedBirthCenter center = parseCenter(row.children()); if (center != null) { allCenters.add(center); } } return allCenters; }
From source file:org.zaizi.sensefy.auth.user.acl.ManifoldACLRequester.java
@PostConstruct public void init() { socketTimeOut = 300000;//from ww w. ja v a 2 s. co m poolSize = 50; // Initialize the connection pool httpConnectionManager = new PoolingClientConnectionManager(); httpConnectionManager.setMaxTotal(poolSize); httpConnectionManager.setDefaultMaxPerRoute(poolSize); BasicHttpParams params = new BasicHttpParams(); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeOut); DefaultHttpClient clientAux = new DefaultHttpClient(httpConnectionManager, params); clientAux.setRedirectStrategy(new DefaultRedirectStrategy()); client = clientAux; }
From source file:ua.pp.msk.cliqr.GetProcessorImpl.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);// w w w .ja va 2s .co m UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new CliQrRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }