Example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

List of usage examples for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy.

Prototype

public DefaultRedirectStrategy() 

Source Link

Usage

From source file:org.easyj.http.EasyRESTHttpClient.java

/**
 * Creates a new instance of EasyRESTHttpClient wrapping the HttpClient and Method in the same class.
 *///from   w w  w.  ja  v a 2s . co m
public EasyRESTHttpClient() {
    client = new DefaultHttpClient();
    requestHeaders = new HashMap<String, Object>();
    parameters = new HashMap<String, Object>();
    ignoreRedirectStatuses = new ArrayList<Integer>();
    response = null;
    entity = null;
    exception = null;
    responseString = "";

    ((DefaultHttpClient) client).setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
            boolean isRedirect = false;
            int responseCode = response.getStatusLine().getStatusCode();
            if (!isIgnoreRedirect() && !ignoreRedirectStatuses.contains(responseCode)) {
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                }
            }

            return isRedirect;
        }
    });
}

From source file:org.alfresco.po.share.util.FileDownloader.java

/**
 * Main method that performs the download operation
 * using HttpClient with WebDriver's cookies.
 * /*from  w ww  . j a  v a2  s  .  c om*/
 * @param path url path to file
 * @throws Exception if error
 */
public void download(final String path, File file) throws Exception {
    URL fileToDownload;
    // Cookie setup
    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    HttpClient client = HttpClientBuilder.create().setRedirectStrategy(redirectStrategy).build();
    HttpEntity entity = null;
    try {
        String myUrl = URLDecoder.decode(path, "UTF-8");
        String fileUrl = myUrl.replace("\\/", "/").replace(" ", "%20");

        fileToDownload = new URL(fileUrl);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, getCookies());
        // Prepare an http get call
        HttpGet httpget = new HttpGet(fileToDownload.toURI());
        if (logger.isDebugEnabled()) {
            logger.debug("Sending GET request for: " + httpget.getURI());
        }
        // Get the response from http get call
        HttpResponse response = client.execute(httpget, localContext);
        int httpStatusCode = response.getStatusLine().getStatusCode();
        if (logger.isDebugEnabled()) {
            logger.debug("HTTP GET request status: " + httpStatusCode);
        }
        // Extract content and stream to file
        entity = response.getEntity();
        InputStream input = entity.getContent();
        if (input != null) {
            FileUtils.copyInputStreamToFile(input, file);
        }
    } catch (MalformedURLException murle) {
        throw new Exception("Unable to reach document", murle);
    } catch (IllegalStateException ise) {
        throw new Exception("State problem", ise);
    } catch (IOException ioe) {
        throw new Exception("Unable to read write file", ioe);
    } catch (URISyntaxException urise) {
        throw new Exception("A uri syntax problem", urise);
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

public HttpAbstract(String userAgent, boolean bFollowRedirect, ProxyHandler proxyHandler) {
    HttpClientBuilder builder = HttpClients.custom();

    redirectStrategy = new DefaultRedirectStrategy();

    if (userAgent != null) {
        userAgent = userAgent.trim();//from  w w  w .j  av a2 s  . c  o m
        if (userAgent.length() > 0)
            builder.setUserAgent(userAgent);
        else
            userAgent = null;
    }
    if (!bFollowRedirect)
        builder.disableRedirectHandling();

    this.proxyHandler = proxyHandler;

    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    credentialsProvider = new BasicCredentialsProvider();
    builder.setDefaultCredentialsProvider(credentialsProvider);

    cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    builder.setDefaultCredentialsProvider(credentialsProvider);
    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

    httpClient = builder.build();

}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }// w  ww  . j  a  va2  s .  com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:org.wisdom.framework.filters.ProxyFilter.java

/**
 * 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/*  w  w  w. j a v  a  2 s  .  c  om*/
 */
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();
}

From source file:io.undertow.servlet.test.security.custom.ServletCustomAuthTestCase.java

@Test
public void testServletCustomFormAuth() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from  w w  w . ja  v  a  2 s .c o m
        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);
        }
    });
    try {
        final String uri = DefaultServer.getDefaultServerURL() + "/servletContext/secured/test";
        HttpGet get = new HttpGet(uri);
        HttpResponse result = client.execute(get);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("Login Page", response);

        BasicNameValuePair[] pairs = new BasicNameValuePair[] { new BasicNameValuePair("j_username", "user1"),
                new BasicNameValuePair("j_password", "password1") };
        final List<NameValuePair> data = new ArrayList<>();
        data.addAll(Arrays.asList(pairs));
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/"
                + CustomAuthenticationMechanism.POST_LOCATION);

        post.setEntity(new UrlEncodedFormEntity(data));

        result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("user1", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.easyj.http.EasyHttpClient.java

/**
 * Creates a new instance of EasyHttpClient wrapping the HttpClient and Method in the same class.
 *//*from w  w  w . jav  a  2 s . com*/
public EasyHttpClient(int maxConnections) {
    this.maxConnections = maxConnections;
    connManager = new ThreadSafeClientConnManager();
    connManager.setMaxTotal(this.maxConnections);

    client = new DefaultHttpClient(connManager);
    requestHeaders = new HashMap<String, Object>();
    parameters = new HashMap<String, Object>();
    ignoreRedirectStatuses = new ArrayList<Integer>();
    response = null;
    entity = null;
    exception = null;
    responseString = "";

    ((DefaultHttpClient) client).setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
            boolean isRedirect = false;
            int responseCode = response.getStatusLine().getStatusCode();
            if (!isIgnoreRedirect() && !ignoreRedirectStatuses.contains(responseCode)) {
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                }
            }

            return isRedirect;
        }
    });
}

From source file:org.commonjava.web.json.test.WebFixture.java

public void disableRedirection() {
    http.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override/* www . java2 s  .  c o m*/
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            return false;
        }
    });
}

From source file:com.bigdata.rdf.sail.webapp.client.BigdataSailNSSWrapper.java

public void init() throws Exception {

    final Map<String, String> initParams = new LinkedHashMap<String, String>();
    {/*  w w w . j ava  2  s .  c  o  m*/

        initParams.put(ConfigParams.NAMESPACE, sail.getDatabase().getNamespace());

        initParams.put(ConfigParams.CREATE, "false");

    }
    // Start server for that kb instance.
    m_fixture = NanoSparqlServer.newInstance(0/* port */, sail.getDatabase().getIndexManager(), initParams);

    m_fixture.start();

    final int port = NanoSparqlServer.getLocalPort(m_fixture);

    // log.info("Getting host address");

    final String hostAddr = NicUtil.getIpAddress("default.nic", "default", true/* loopbackOk */);

    if (hostAddr == null) {

        throw new RuntimeException("Could not identify network address for this host.");

    }

    m_rootURL = new URL("http", hostAddr, port, ""/* contextPath */
    ).toExternalForm();

    m_serviceURL = new URL("http", hostAddr, port, BigdataStatics.getContextPath()).toExternalForm();

    if (log.isInfoEnabled())
        log.info("Setup done: \nrootURL=" + m_rootURL + "\nserviceURL=" + m_serviceURL);

    //        final HttpClient httpClient = new DefaultHttpClient();

    //        m_cm = httpClient.getConnectionManager();

    m_cm = DefaultClientConnectionManagerFactory.getInstance().newInstance();

    final DefaultHttpClient httpClient = new DefaultHttpClient(m_cm);
    m_httpClient = httpClient;

    /*
     * Ensure that the client follows redirects using a standard policy.
     * 
     * Note: This is necessary for tests of the webapp structure since the
     * container may respond with a redirect (302) to the location of the
     * webapp when the client requests the root URL.
     */
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());

    m_repo = new RemoteRepositoryManager(m_serviceURL, m_httpClient,
            sail.getDatabase().getIndexManager().getExecutorService());

}