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

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

Introduction

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

Prototype

LaxRedirectStrategy

Source Link

Usage

From source file:com.atlbike.etl.service.ClientFormLogin.java

/**
 * @param args//from   w  w w.  j av a  2 s .c  o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String authenticityToken = "";
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
    try {
        HttpGet httpget = new HttpGet("https://atlbike.nationbuilder.com/login");
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("Login form get: " + response1.getStatusLine());
            // EntityUtils.consume(entity);
            String content = EntityUtils.toString(entity);
            Document doc = Jsoup.parse(content);
            Elements metaElements = doc.select("META");
            for (Element elem : metaElements) {
                System.out.println(elem);
                if (elem.hasAttr("name") && "csrf-token".equals(elem.attr("name"))) {
                    System.out.println("Value: " + elem.attr("content"));
                    authenticityToken = elem.attr("content");
                }
            }

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("https://atlbike.nationbuilder.com/forms/user_sessions"))
                .addParameter("email_address", "").addParameter("user_session[email]", "email@domain")
                .addParameter("user_session[password]", "magicCookie")
                .addParameter("user_session[remember_me]", "1").addParameter("commit", "Sign in with email")
                .addParameter("authenticity_token", authenticityToken).build();
        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();
            // for (Header h : response2.getAllHeaders()) {
            // System.out.println(h);
            // }
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }

        httpget = new HttpGet(
                // HttpUriRequest file = RequestBuilder
                // .post()
                // .setUri(new URI(
                "https://atlbike.nationbuilder.com/admin/membership_types/14/download");
        // .build();
        // CloseableHttpResponse response3 = httpclient.execute(file);
        CloseableHttpResponse response3 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response3.getEntity();
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("File Get: " + response3.getStatusLine());
            saveEntity(entity);
            // EntityUtils.consume(entity);

            System.out.println("Post file get cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response3.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:drmaas.sandbox.http.LoginTest.java

public static void main(String[] args) throws Exception {

    //1. For SSL/*from   w  w  w  . j  a  v  a 2  s.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:com.cloud.utils.rest.HttpClientHelper.java

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();
}

From source file:edu.kit.dama.rest.dataorganization.services.impl.util.HttpDownloadHandler.java

@Override
public Response prepareStream(URL pUrl) throws IOException {
    try {//from w  w  w . j  a  v a 2s.c o m
        final CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
                .build();

        HttpGet httpget = new HttpGet(pUrl.toURI());

        final CloseableHttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        String contentType = entity.getContentType().getValue();
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        LOGGER.debug("Using content type '{}' to stream URL content to client.", contentType);
        final InputStream is = entity.getContent();

        final StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                try {
                    byte[] data = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(data)) != -1) {
                        os.write(data, 0, bytesRead);
                    }
                } finally {
                    response.close();
                    httpclient.close();
                }
            }
        };
        return Response.ok(stream, contentType).build();
    } catch (URISyntaxException ex) {
        throw new IOException("Failed to prepare download stream for URL " + pUrl, ex);
    }
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

private CloseableHttpClient createClient() {

    return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:com.github.aistomin.http.PostRequest.java

@Override
public String execute() throws Exception {
    final Request request = Request.Post(this.resource);
    for (final Map.Entry<String, String> item : this.heads.entrySet()) {
        request.addHeader(item.getKey(), item.getValue());
    }//from   w w  w .j a v  a  2 s . co  m
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new LaxRedirectStrategy());
    builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
        public boolean retryRequest(final HttpResponse response, final int count, final HttpContext context) {
            return count <= PostRequest.RETRY_COUNT;
        }

        public long getRetryInterval() {
            return PostRequest.RETRY_INTERVAL;
        }
    });
    return Executor.newInstance(builder.build()).execute(request).returnContent().asString();
}

From source file:nl.b3p.viewer.admin.ViewerAdminLockoutIntegrationTest.java

/**
 * initialize http client.//from ww w. jav  a2  s. c  o m
 */
@BeforeClass
public static void setupClient() {
    //client = HttpClientBuilder.create().build();
    client = HttpClients.custom().useSystemProperties().setUserAgent("brmo integration test")
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCookieStore(new BasicCookieStore())
            .build();
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

private CloseableHttpClient createAuthenticatedClient() {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(config.getUser(), config.getApiKey()));

    return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent)
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider)
            .build();/*from   w ww  .  ja  v a2s  .  c  om*/
}

From source file:org.apache.sling.hapi.client.impl.AbstractHtmlClientImpl.java

public AbstractHtmlClientImpl(String baseUrl) throws URISyntaxException {
    this(HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(), baseUrl);
}