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

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

Introduction

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

Prototype

public DefaultRedirectHandler() 

Source Link

Usage

From source file:it.restrung.rest.misc.HttpClientFactory.java

/**
 * Private helper to initialize an http client
 *
 * @return the initialize http client//from  www.j a v a 2  s . c o m
 */
private static synchronized DefaultHttpClient initializeClient() {
    //prepare for the https connection
    //call this in the constructor of the class that does the connection if
    //it's used multiple times
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    schemeRegistry.register(new Scheme("https", new FakeSocketFactory(), 443));

    HttpParams params;
    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");

    // ignore that the ssl cert is self signed
    ThreadSafeClientConnManager clientConnectionManager = new ThreadSafeClientConnManager(params,
            schemeRegistry);

    instance = new DefaultHttpClient(clientConnectionManager, params);
    instance.setRedirectHandler(new DefaultRedirectHandler()); //If the link has a redirect
    return instance;
}

From source file:org.webcat.notifications.googlevoice.AsyncURLConnection.java

/**
 * Initializes a new URL connection.//  w w w .j  a v  a2  s . c o m
 *
 * @param request the HTTP request
 * @param delegate the delegate
 * @param startImmediately true to start the request immediately; false to
 *     not start it until the {@link #start()} method is called
 */
public AsyncURLConnection(HttpUriRequest request, URLConnectionDelegate delegate, boolean startImmediately) {
    this.request = request;
    this.delegate = delegate;

    client = new DefaultHttpClient();
    client.setRedirectHandler(new DefaultRedirectHandler());
    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (startImmediately) {
        start();
    }
}

From source file:com.hoccer.http.AsyncHttpRequest.java

private void setHttpClient(DefaultHttpClient pHttpClient) {
    mHttpClient = pHttpClient;/*from   w  ww .  j  av  a  2s  .c  om*/

    // overwrite user-agent if it's not already customized
    Object userAgent = mHttpClient.getParams().getParameter("http.useragent");
    if (userAgent == null || userAgent.toString().contains("Apache-HttpClient")) {
        mHttpClient.getParams().setParameter("http.useragent", "Hoccer Java API");
    }

    // remember redirects
    mHttpClient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            mRequest.setURI(uri);
            return uri;
        }
    });
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

protected GVCommunicator(Context context) {
    mySettings = SettingsProvider.getInstance(context);

    myUsername = mySettings.getGVUsername();
    myPassword = mySettings.getGVPassword();

    myClient = new DefaultHttpClient();
    myClient.setRedirectHandler(new DefaultRedirectHandler());
    myClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
}

From source file:org.ebayopensource.twin.TwinConnection.java

private HttpClient getClient() {
    synchronized (TwinConnection.class) {
        if (connManager == null) {
            DefaultHttpClient client = new DefaultHttpClient();
            params = client.getParams().copy();
            params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(50));
            params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
            connManager = new ThreadSafeClientConnManager(params,
                    client.getConnectionManager().getSchemeRegistry());
        }//from   w  w w.  j  a v a 2s .  c o m
    }
    DefaultHttpClient client = new DefaultHttpClient(connManager, params);
    client.setRedirectHandler(new DefaultRedirectHandler());
    return client;
}

From source file:org.wso2.identity.integration.test.saml.SAMLInvalidIssuerTestCase.java

@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {
    super.init();

    ConfigurationContext configContext = ConfigurationContextFactory
            .createConfigurationContextFromFileSystem(null, null);
    applicationManagementServiceClient = new ApplicationManagementServiceClient(sessionCookie, backendURL,
            configContext);//from w  w  w .  j a va 2  s.c  o  m
    remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie);

    isSAMLReturned = false;

    httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {

            if (response == null) {
                throw new IllegalArgumentException("HTTP Response should not be null");
            }
            //get the location header to find out where to redirect to
            Header locationHeader = response.getFirstHeader("Location");
            if (locationHeader == null) {
                // got a redirect resp, but no location header
                throw new ProtocolException(
                        "Received redirect resp " + response.getStatusLine() + " but no location header");
            }

            URL url = null;
            try {
                url = new URL(locationHeader.getValue());
                if (SAML_ERROR_NOTIFICATION_PATH.equals(url.getPath())
                        && url.getQuery().contains("SAMLResponse")) {
                    isSAMLReturned = true;
                }
            } catch (MalformedURLException e) {
                throw new ProtocolException("Invalid redirect URI: " + locationHeader.getValue(), e);
            }

            return super.getLocationURI(response, context);
        }
    });

    createUser();
    createApplication();

    //Starting tomcat
    log.info("Starting Tomcat");
    tomcatServer = getTomcat();

    //TODO: Uncomment below once the tomcat dependency issue is resolved
    //        URL resourceUrl = getClass()
    //                .getResource(File.separator + "samples" + File.separator + "org.wso2.sample.is .sso.agent.war");
    URL resourceUrl = getClass()
            .getResource(File.separator + "samples" + File.separator + "travelocity.com.war");
    startTomcat(tomcatServer, "/travelocity.com", resourceUrl.getPath());

}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

public boolean login(String username, String password) {
    myError = "";
    if (username.trim().length() == 0 || password.trim().length() == 0) {
        myError = "No Google Voice login information saved!";
        return false;
    }// w ww. j a v  a 2 s  . c om

    String token;

    myUsername = username;
    myPassword = password;

    myClient = new DefaultHttpClient();
    myClient.setRedirectHandler(new DefaultRedirectHandler());
    myClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new BasicNameValuePair("accountType", "GOOGLE"));
    data.add(new BasicNameValuePair("Email", username));
    data.add(new BasicNameValuePair("Passwd", password));
    data.add(new BasicNameValuePair("service", "grandcentral"));
    data.add(new BasicNameValuePair("source", "com-evancharlton-googlevoice-android-GV"));

    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
    myError = "";
    try {
        post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
        HttpResponse response = myClient.execute(post);
        BufferedReader is = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while ((line = is.readLine()) != null) {
            if (line.startsWith("Auth")) {
                token = line.substring(5);
                storeToken(token);
                break;
            }
        }
        is.close();
        HttpGet get = new HttpGet("https://www.google.com/voice/m/i/voicemail?p=10000");
        response = myClient.execute(get);
        is = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        Pattern rnrse = Pattern.compile("name=\"_rnr_se\"\\s*value=\"([^\"]+)\"");
        Pattern gvn = Pattern.compile("<b class=\"ms3\">([^<]+)</b>");
        Matcher m;
        boolean valid = false;
        boolean gvnvalid = false;
        while ((line = is.readLine()) != null) {
            if (line.indexOf("The username or password you entered is incorrect.") >= 0) {
                myError = "The username or password you entered is incorrect.";
                break;
            } else {
                if (line.indexOf("google.com/support/voice/bin/answer.py?answer=142423") >= 0) {
                    myError = "This Google Account does not have a Google Voice account.";
                    break;
                } else {
                    if (!gvnvalid) {
                        m = gvn.matcher(line);
                        if (m.find()) {
                            myGVNumber = normalizeNumber(m.group(1));
                            gvnvalid = true;
                        }
                    }

                    if (!valid) {
                        m = rnrse.matcher(line);
                        if (m.find()) {
                            myError = "";
                            myToken = m.group(1);
                            valid = true;
                        }
                    }

                    if (valid && gvnvalid)
                        break;
                }
            }
        }
        is.close();
        return valid;
    } catch (Exception e) {
        e.printStackTrace();
        myError = "Network error! Try cycling wi-fi (if enabled).";
    }

    if (myError.length() > 0)
        Log.e("GV Login Error", myError);
    return false;
}

From source file:org.openpipeline.pipeline.connector.webcrawler.Fetcher.java

/**
 * Fetches the data associated with the next URL.
 * /*  w w w.  ja  v a2s. com*/
 * @param nextUrlItem
 *            containing the next URL to crawl
 * 
 * @return action based on the status code of the HttpClient, robots safety
 *         check, max number of redirects, max number of fetch attempts
 */
public int fetch(LinkDBRecord nextUrlItem) {

    if (nextUrlItem == null) {
        return HttpResultMapper.ACTION_DELETE;
    }

    if (client == null) {
        throw new RuntimeException("Fetcher not initialized.");
    }

    String nextUrl = nextUrlItem.getNextUrl();
    redirectUrl = nextUrl;
    HttpResponse httpResponse = null;
    HttpGet get = null;
    lastModified = 0;

    try {
        /*
         * Check the compliance with allow/disallow directives.
         */
        UrlItem item = new UrlItem(nextUrlItem.getNextUrl());

        boolean robotsSafe = robotsDirectives.allowed(item);
        if (!robotsSafe) {
            if (debug) {
                logger.debug("Robots denied, next URL: " + nextUrl);
            }
            return HttpResultMapper.ACTION_DELETE;
        }
        /*
         * Check the compliance with visit-time directives.
         */
        boolean visitTimeSafe = robotsDirectives.visitTimeOK();
        if (!visitTimeSafe) {
            if (debug) {
                logger.debug("Robots visit time denied, next URL: " + nextUrl);
            }
            return HttpResultMapper.ACTION_SKIP;
        }

        int status = -1;
        int numRedirects = 0;

        while (true) {

            get = new HttpGet();

            /* Set uri for the next execution of get */
            URI uri = new URI(nextUrl);
            get.setURI(uri);

            /*
             * Check crawl delay. If the fetcher follows the redirect URL it
             * will also observe the crawl delay
             */
            long waitTime = robotsDirectives.crawlDelayTime(lastFetchTimeThisDomain);

            if (waitTime > 0) {
                try {
                    Thread.sleep(waitTime);
                } catch (InterruptedException e) {
                    logger.error("Exception in fetcher in thread.sleep, next URL: " + nextUrl + ". Message: "
                            + e.getMessage());
                }
            }

            /* Execute get method */
            DefaultRedirectHandler redirectHandler = new DefaultRedirectHandler();
            client.setRedirectHandler(redirectHandler);

            HttpContext localContext = new BasicHttpContext();

            httpResponse = client.execute(get, localContext);
            if (httpResponse == null) {
                break;
            }

            Header lastModHeader = httpResponse.getFirstHeader("last-modified");
            if (lastModHeader != null) {
                String lastModifiedDate = lastModHeader.getValue();
                Date date = format.parse(lastModifiedDate);
                lastModified = date.getTime();
            }

            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine == null) {
                /* Should not happen after execute */
                status = -1;
            } else {
                status = httpResponse.getStatusLine().getStatusCode();
            }

            lastFetchTimeThisDomain = System.currentTimeMillis();

            HttpEntity entity = httpResponse.getEntity();

            if (HttpResultMapper.permanentRedirect(status) || HttpResultMapper.temporaryRedirect(status)) {
                /*
                 * The fetcher follows a redirect until the maximum number
                 * of redirects is reached.
                 */
                if (numRedirects == maxNumberOfRedirects) {
                    break;
                }

                /* Update the URL to be fetched */
                URI redirectURI = redirectHandler.getLocationURI(httpResponse, localContext);

                String newUrl = redirectURI.toString();
                numRedirects++;

                /*
                 * In case of a permanent redirect, the fetcher asks the URL
                 * filter whether to follow it or not. The fetcher follows
                 * all temporary redirects.
                 */
                if (HttpResultMapper.permanentRedirect(status)) {

                    boolean redirectUrlOK = urlFilter.checkCanonicalForm(newUrl, nextUrl);

                    /*
                     * Only follows the permanent redirects which are
                     * different because of the formatting to the canonical
                     * form such as removing the trailing slash
                     */
                    if (!redirectUrlOK) {
                        /* Permanent redirect, keep the redirect URL */
                        redirectUrl = newUrl;
                        break;
                    }
                }
                /*
                 * If the permanent redirect URL differs just in formatting,
                 * or if temporary redirect follow it.
                 * 
                 * The redirect URL becomes nextURL for the next iteration
                 * of the while loop.
                 */
                nextUrl = newUrl;

                if (debug) {
                    logger.debug("Fetcher: had a redirect, redirect URL: " + nextUrl + ", status: " + status);
                }
            } else {
                /*
                 * get's responseBody contains data if success and is null
                 * otherwise
                 */
                // TODO retry if
                // exception?

                if (entity != null) {

                    long inputSize = entity.getContentLength();

                    if (inputSize > 0 && inputSize >= maxFileSize) {
                        throw new RuntimeException("Fetcher exception: data exceeds the max file size.");
                    }
                    /* Often the data length is not known */
                    inputStream = getData(entity);
                }
                break;
            }
            /*
             * Need to release the current connection, otherwise client does
             * not work
             */
            entity.consumeContent();
        }

        /*
         * Decide on action after the while loop is done, possibly done with
         * redirects
         */
        int action = HttpResultMapper.getHttpCodeResult(status);

        int fetchAttempts = nextUrlItem.getFetchAttempts();
        if (action != HttpResultMapper.ACTION_FINALIZE && fetchAttempts == maxNumberOfFetchAttempts) {
            /*
             * Remove items which have too many fetch attempts: redirects,
             * skip etc
             */
            action = HttpResultMapper.ACTION_DELETE;
        } else if (numRedirects == maxNumberOfRedirects) {
            /*
             * Avoid following too many redirects
             */
            action = HttpResultMapper.ACTION_DELETE;
        }

        return action;

    } catch (Throwable e) {
        /*
         * Currently, no re-tries are implemented. The HttpClient
         * automatically tries to recover from safe exceptions.
         */

        if (e instanceof org.apache.http.conn.ConnectTimeoutException) {
            return HttpResultMapper.ACTION_SKIP;
        }
        return HttpResultMapper.ACTION_DELETE;
    } finally {
        if (get != null) {
            get.abort();
        }
    }
}

From source file:com.akop.bach.parser.LiveParser.java

@Override
protected DefaultHttpClient createHttpClient(Context context) {
    mLastRedirectedUrl = null;//ww w. j  av a 2s.  c o m

    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            if (uri != null)
                mLastRedirectedUrl = uri.toString();

            return uri;
        }
    });

    client.getCookieSpecs().register("lenient", new CookieSpecFactory() {
        public CookieSpec newInstance(HttpParams params) {
            return new LenientCookieSpec();
        }
    });

    HttpClientParams.setCookiePolicy(client.getParams(), "lenient");

    return client;
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.RTCClient.java

private void setRedirectStategy() {
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override/*  ww w.j av  a2s.c  o m*/
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            boolean isRedirect = super.isRedirectRequested(response, context);
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });
}