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:biz.webgate.tools.urlfetcher.URLFetcher.java

public static PageAnalyse analyseURL(String url, int maxPictureHeight) throws FetcherException {
    PageAnalyse analyse = new PageAnalyse(url);
    HttpClient httpClient = null;//w  w  w  . java2  s  . c  o m
    try {
        httpClient = new DefaultHttpClient();
        ((DefaultHttpClient) httpClient).setRedirectStrategy(new DefaultRedirectStrategy());
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-Type", "text/html; charset=utf-8");
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == STATUS_OK) {
            HttpEntity entity = response.getEntity();
            parseContent(maxPictureHeight, analyse, entity.getContent());

        } else {
            throw new FetcherException("Response from WebSite is :" + statusCode);
        }
    } catch (IllegalStateException e) {
        throw new FetcherException(e);
    } catch (FetcherException e) {
        throw e;
    } catch (Exception e) {
        throw new FetcherException(e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return analyse;
}

From source file:org.carrot2.util.httpclient.HttpRedirectStrategy.java

public RedirectStrategy value() {
    switch (this) {
    case NO_REDIRECTS:
        return new RedirectStrategy() {
            public HttpUriRequest getRedirect(HttpRequest req, HttpResponse resp, HttpContext ctx)
                    throws ProtocolException {
                throw new UnsupportedOperationException();
            }//from   w w  w . j  a v a  2s.  c o  m

            public boolean isRedirected(HttpRequest req, HttpResponse resp, HttpContext ctx)
                    throws ProtocolException {
                return false;
            }
        };

    case FOLLOW:
        return new DefaultRedirectStrategy();
    }

    throw new RuntimeException();
}

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);
        }//  w  w  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.yaauie.unfurl.UrlExpander.java

public UrlExpander(final HttpClientConnectionManager connectionManager) {
    this.httpClient = HttpClients.custom().setConnectionManager(connectionManager)
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:org.cloudfoundry.identity.uaa.util.UaaHttpRequestUtils.java

protected static HttpClientBuilder getClientBuilder(boolean skipSslValidation) {
    HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
            .setRedirectStrategy(new DefaultRedirectStrategy());
    if (skipSslValidation) {
        builder.setSslcontext(getNonValidatingSslContext());
    }/*from w ww . java2s.  c o  m*/
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    return builder;
}

From source file:com.rogiel.httpchannel.http.HttpContext.java

public HttpContext() {
    // default configuration
    params = new ClientParamBean(client.getParams());
    params.setHandleRedirects(true);//  w w w  . j ava 2  s . c om
    params.setAllowCircularRedirects(true);
    params.setRejectRelativeRedirect(false);
    params.setMaxRedirects(10);

    // browser behavior
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response,
                org.apache.http.protocol.HttpContext context) throws ProtocolException {
            return response.containsHeader("Location");
        }
    });
}

From source file:com.vina.hlexchang.ClientRequestHelper.java

public void setProxy(String host, int port) {
    HttpHost proxy = new HttpHost(host, port, "http");
    mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    // mClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    mClient.getParams().setParameter(ClientPNames.MAX_REDIRECTS, 100);

    mClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from  w  w w .ja v  a 2s.  c  o m
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
            boolean isRedirect = false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });
}

From source file:juzu.impl.bridge.context.AbstractContextClientTestCase.java

protected void test(URL initialURL, String kind) throws Exception {
    driver.get(initialURL.toString());//w  w w .  ja v a2  s . c om
    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:org.picketlink.test.identity.federation.bindings.wildfly.UndertowTestCase.java

protected void setupHttpClient() {
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override/*from   w w  w  .ja va 2  s  .co  m*/
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == 302) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });
}

From source file:com.seajas.search.contender.http.ParameterizableHttpClient.java

/**
 * Default constructor.//from   w  w w  .  j a v a2 s. c o  m
 * 
 * @param connectionManager
 * @param parameters
 * @param httpHost
 * @param httpPort
 * @param userAgent
 * @param connectionTimeout
 */
public ParameterizableHttpClient(final ClientConnectionManager connectionManager, final HttpParams parameters,
        final String httpHost, final Integer httpPort, final String userAgent,
        final Integer connectionTimeout) {
    super(connectionManager, parameters);

    if (!StringUtils.isEmpty(httpHost))
        ConnRouteParams.setDefaultProxy(getParams(), new HttpHost(httpHost, httpPort));
    HttpProtocolParams.setUserAgent(getParams(), userAgent);

    if (connectionTimeout > 0) {
        HttpConnectionParams.setSoTimeout(getParams(), connectionTimeout);
        HttpConnectionParams.setConnectionTimeout(getParams(), connectionTimeout);
        HttpClientParams.setConnectionManagerTimeout(getParams(), connectionTimeout);
    }

    setRedirectStrategy(new DefaultRedirectStrategy());
}