Example usage for org.apache.http.client RedirectHandler RedirectHandler

List of usage examples for org.apache.http.client RedirectHandler RedirectHandler

Introduction

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

Prototype

RedirectHandler

Source Link

Usage

From source file:com.geertvanderploeg.kiekeboek.client.NetworkUtilities.java

/**
 * Configures the httpClient to connect to the URL provided.
 */// w w w  . ja v a  2s .  c  om
public static HttpClient getHttpClient() {
    if (httpClient == null) {
        httpClient = new DefaultHttpClient() {

            // No redirects
            @Override
            protected RedirectHandler createRedirectHandler() {
                return new RedirectHandler() {
                    @Override
                    public URI getLocationURI(HttpResponse response, HttpContext context)
                            throws ProtocolException {
                        return null;
                    }

                    @Override
                    public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                        return false;
                    }
                };
            }
        };
        final HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, REGISTRATION_TIMEOUT);
        ConnManagerParams.setTimeout(params, REGISTRATION_TIMEOUT);
    }
    return httpClient;
}

From source file:de.taxilof.UulmLoginAgent.java

/**
 * perform the Login & necessary Checks
 *//*ww  w.j  a  v  a2 s.c  om*/
public void login() {
    // setting up my http client
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Linux; U; Android; uulmLogin " + context.getString(R.string.app_version) + ")");
    // disable redirects in client, used from isLoggedIn method
    client.setRedirectHandler(new RedirectHandler() {
        public URI getLocationURI(HttpResponse arg0, HttpContext arg1) throws ProtocolException {
            return null;
        }

        public boolean isRedirectRequested(HttpResponse arg0, HttpContext arg1) {
            return false;
        }
    });

    // get IP
    String ipAddress = getIp();
    if (ipAddress == null) {
        Log.d("uulmLogin", "Could not get IP Address, aborting.");
        return;
    }
    Log.d("uulmLogin", "Got IP: " + ipAddress + ", continuing.");

    // check if IP prefix is wrong
    if (!(ipAddress.startsWith(context.getString(R.string.ip_prefix)))) {
        Log.d("uulmLogin", "Wrong IP Prefix.");
        return;
    }

    // check the SSID
    String ssid = getSsid();
    if (!(context.getString(R.string.ssid).equals(ssid))) {
        Log.d("uulmLogin", "Wrong SSID, aborting.");
        return;
    }

    // check if we are already logged in
    if (isLoggedIn(client, 5)) {
        Log.d("uulmLogin", "Already logged in, aborting.");
        return;
    }

    // try to login via GET Request
    try {
        // login
        HttpGet get = new HttpGet(String.format("%s?username=%s&password=%s&login=Anmelden",
                context.getString(R.string.capo_uri), username, URLEncoder.encode(password)));
        @SuppressWarnings("unused")
        HttpResponse response = client.execute(get);
        Log.d("uulmLogin", "Login done, HttpResponse:" + HttpHelper.request(response));
    } catch (SSLException ex) {
        Log.w("uulmLogin", "SSL Error while sending Login Request: " + ex.toString());
        if (notifyFailure)
            notify("Login to Welcome failed", "SSL Error: could not verify Host", true);
        return;
    } catch (Exception e) {
        Log.w("uulmLogin", "Error while sending Login Request: " + e.toString());
        if (notifyFailure)
            notify("Login to Welcome failed", "Error while sending Login Request.", true);
        return;
    }

    // should be logged in now, but we check it now, just to be sure
    if (isLoggedIn(client, 2)) {
        if (notifySuccess)
            notify("Login to welcome successful.", "Your IP: " + ipAddress, false);
        Log.d("uulmLogin", "Login successful.");
    } else {
        if (notifyFailure)
            notify("Login to welcome failed.", "Maybe wrong Username/Password?", true);
        Log.w("uulmLogin", "Login failed, wrong user/pass?");
    }
}

From source file:com.hly.component.download.DownloadTransaction.java

private void getRedirectUrl(final String url) throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new RedirectHandler() {

        @Override/*from w  w  w  .j  a  va2s.com*/
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            return null;
        }

        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            if (302 == response.getStatusLine().getStatusCode()
                    || 301 == response.getStatusLine().getStatusCode()) {
                Header[] headers = response.getHeaders("Location");
                if (headers != null && headers.length > 0) {
                    mQueryUri = headers[0].getValue();
                    Log.d(TAG, "mQueryUri:" + mQueryUri);
                    if (!T.ckIsEmpty(mQueryUri) && !mQueryUri.equals(mRedirectUri)) {
                        mRedirectUri = mQueryUri;
                        notifyUrlChange();
                    }
                }
            }
            return false;
        }
    });
    HttpGet request = new HttpGet(url);
    httpClient.execute(request);
}

From source file:at.alladin.rmbt.client.v2.task.HttpProxyTask.java

/**
 * /*from   w w  w . j a  v a 2s  .c  om*/
 * @return
 */
private QoSTestResult httpGet(final QoSTestResult result) throws Exception {
    final HttpGet httpGet = new HttpGet(new URI(this.target));

    if (range != null && range.startsWith("bytes")) {
        httpGet.addHeader("Range", range);
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout
    HttpConnectionParams.setConnectionTimeout(httpParameters, (int) (connectionTimeout / 1000000));
    // Set the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, (int) (downloadTimeout / 1000000));

    System.out.println("Downloading: " + target);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    //prevent redirects:
    httpClient.setRedirectHandler(new RedirectHandler() {

        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            return false;
        }

        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            return null;
        }
    });

    Thread timeoutThread = new Thread(new Runnable() {

        public void run() {
            try {
                System.out.println("HTTP PROXY TIMEOUT THREAD: " + downloadTimeout + " ms");
                Thread.sleep((int) (downloadTimeout / 1000000));

                if (!downloadCompleted.get()) {
                    if (httpGet != null && !httpGet.isAborted()) {
                        httpGet.abort();
                    }
                    timeOutReached.set(true);
                    System.out.println("HTTP PROXY TIMEOUT REACHED");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    timeoutThread.start();

    String hash = null;
    long duration = 0;

    try {
        final long start = System.nanoTime();
        HttpResponse response = httpClient.execute(httpGet);

        //get the content:
        long contentLength = -1;
        if (getQoSTest().getTestSettings().getCacheFolder() != null) {
            File cacheFile = new File(getQoSTest().getTestSettings().getCacheFolder(), "proxy" + threadId);
            contentLength = writeFileFromInputStream(response.getEntity().getContent(), cacheFile);
            duration = System.nanoTime() - start;
            hash = generateChecksum(cacheFile);
            cacheFile.delete();
        } else {
            //get Content:
            String content = getStringFromInputStream(response.getEntity().getContent());
            duration = System.nanoTime() - start;
            //calculate md5 hash:
            hash = generateChecksum(content.getBytes("UTF-8"));
        }

        //result.getResultMap().put(RESULT_DURATION, (duration / 1000000));
        result.getResultMap().put(RESULT_STATUS, response.getStatusLine().getStatusCode());
        result.getResultMap().put(RESULT_LENGTH, contentLength);

        StringBuilder header = new StringBuilder();

        for (Header h : response.getAllHeaders()) {
            header.append(h.getName());
            header.append(": ");
            header.append(h.getValue());
            header.append("\n");
        }

        result.getResultMap().put(RESULT_HEADER, header.toString());
    } catch (Exception e) {
        e.printStackTrace();
        result.getResultMap().put(RESULT_STATUS, "");
        result.getResultMap().put(RESULT_LENGTH, 0);
        result.getResultMap().put(RESULT_HEADER, "");
    } finally {
        if (timeOutReached.get()) {
            result.getResultMap().put(RESULT_HASH, "TIMEOUT");
        } else if (hash != null) {
            result.getResultMap().put(RESULT_HASH, hash);
        } else {
            result.getResultMap().put(RESULT_HASH, "ERROR");
        }
    }

    result.getResultMap().put(RESULT_RANGE, range);
    result.getResultMap().put(RESULT_TARGET, target);

    return result;
}

From source file:me.code4fun.roboq.Request.java

protected HttpClient createHttpClient(int method, String url, Options opts) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // retry count
    int retryCount1 = selectValue(retryCount, prepared != null ? prepared.retryCount : null, 1);
    if (retryCount1 <= 0)
        retryCount1 = 1;//  www.j a va  2  s .  co m
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retryCount1, false));

    // redirect
    boolean redirect1 = selectValue(redirect, prepared != null ? prepared.redirect : null, true);
    if (redirect1) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler());
    } else {
        httpClient.setRedirectHandler(new RedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) {
                return false;
            }

            @Override
            public URI getLocationURI(HttpResponse httpResponse, HttpContext httpContext) {
                return null;
            }
        });
    }

    // 
    Integer connTimeout1 = selectValue(connectionTimeout, prepared != null ? prepared.connectionTimeout : null,
            20000);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connTimeout1);

    // Socket
    Integer soTimeout1 = selectValue(soTimeout, prepared != null ? prepared.soTimeout : null, 0);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout1);

    return httpClient;
}

From source file:eu.nullbyte.android.urllib.Urllib.java

public void setFollowRedirects(boolean follow) {
    httpclient.setRedirectHandler(follow ? new DefaultRedirectHandler() : new RedirectHandler() {
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            return null;
        }// www  . j a v a2s.c o m

        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            return false;
        }
    });
}

From source file:cm.aptoide.pt.ManageRepos.java

private returnStatus checkServerConnection(String uri, String user, String pwd) {
    Log.d("Aptoide-ManageRepo", "checking connection for: " + uri + "  with credentials: " + user + " " + pwd);

    int result;/*from   www .j  a  v a  2  s. c o m*/

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters);

    //      DefaultHttpClient mHttpClient = Threading.getThreadSafeHttpClient();

    mHttpClient.setRedirectHandler(new RedirectHandler() {
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            return false;
        }

        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            return null;
        }
    });

    HttpGet mHttpGet = new HttpGet(uri + "/info.xml");

    //        SharedPreferences sPref = this.getSharedPreferences("aptoide_prefs", Context.MODE_PRIVATE);
    //      String myid = sPref.getString("myId", "NoInfo");
    //      String myscr = sPref.getInt("scW", 0)+"x"+sPref.getInt("scH", 0);

    //        mHttpGet.setHeader("User-Agent", "aptoide-" + this.getString(R.string.ver_str)+";"+ Configs.TERMINAL_INFO+";"+myscr+";id:"+myid+";"+sPref.getString(Configs.LOGIN_USER_NAME, ""));

    try {
        if (user != null && pwd != null) {
            URL mUrl = new URL(uri);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(user, pwd));
        }

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

        Header[] azz = mHttpResponse.getHeaders("Location");
        if (azz.length > 0) {
            String newurl = azz[0].getValue();

            mHttpGet = null;
            mHttpGet = new HttpGet(newurl);

            if (user != null && pwd != null) {
                URL mUrl = new URL(newurl);
                mHttpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(mUrl.getHost(), mUrl.getPort()),
                        new UsernamePasswordCredentials(user, pwd));
            }

            mHttpResponse = null;
            mHttpResponse = mHttpClient.execute(mHttpGet);
        }

        result = mHttpResponse.getStatusLine().getStatusCode();

        if (result == 200) {
            return returnStatus.OK;
        } else if (result == 401) {
            return returnStatus.BAD_LOGIN;
        } else {
            return returnStatus.FAIL;
        }
    } catch (ClientProtocolException e) {
        return returnStatus.EXCEPTION;
    } catch (IOException e) {
        return returnStatus.EXCEPTION;
    } catch (IllegalArgumentException e) {
        return returnStatus.EXCEPTION;
    } catch (Exception e) {
        return returnStatus.EXCEPTION;
    }
}

From source file:org.csp.everyaware.internet.StoreAndForwardService.java

/***************** GET ENDPOINT ADDRESS FROM REDIRECT SERVER **************************/

public void getServer()
        throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException {
    Log.d("StoreAndForwardService", "getServer()");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(Constants.REDIRECT_ADDR);
    httpClient.setRedirectHandler(new RedirectHandler() {
        @Override/*from  w  w  w  . j  a  v a  2s  .  c  om*/
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            Log.d("StoreAndForwardService", "getServer() - getLocationURI()");
            return null;
        }

        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) throws ParseException {
            String responseBody = null;

            try {
                responseBody = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }

            if (responseBody != null) {
                Log.d("StoreAndForwardService",
                        "getServer() - isRedirectRequested()--> status line: " + response.getStatusLine());

                if (response.getStatusLine().getStatusCode() == 302) {
                    Header[] locHeader = response.getHeaders("Location");
                    if ((locHeader != null) && (locHeader.length > 0)) {
                        Utils.report_url = locHeader[0].getValue();
                        Log.d("StoreAndForwardService",
                                "getServer() - isRedirectRequested()--> report url: " + Utils.report_url);
                    }

                    Header[] countryHeader = response.getHeaders("Country");
                    if ((countryHeader != null) && (countryHeader.length > 0)) {
                        Utils.report_country = countryHeader[0].getValue();
                        Log.d("StoreAndForwardService",
                                "getServer() - isRedirectRequested()--> report country: "
                                        + Utils.report_country);
                    }
                } else
                    Log.d("StoreAndForwardService",
                            "getServer() - isRedirectRequested()--> redirect server response is WRONG!");
            } else
                Log.d("StoreAndForwardService",
                        "getServer() - isRedirectRequested()--> response body from redirect server is NULL!");

            return false;
        }
    });

    httpClient.execute(httpPost);
}

From source file:de.escidoc.core.test.aa.AaTestBase.java

/**
 * Returns the status-code after calling the given url.
 * /*from  w w w  . j  a  v  a 2 s .c  o m*/
 * @param url
 *            The url to call.
 * @return int status-code.
 * @throws Exception
 *             If anything fails.
 */
private int getStatusCode(final String url) throws Exception {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.removeRequestInterceptorByClass(RequestAddCookies.class);
    httpClient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpClient.setRedirectHandler(new RedirectHandler() {
        @Override
        public URI getLocationURI(final HttpResponse response, final HttpContext context)
                throws ProtocolException {
            return null;
        }

        @Override
        public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
            return false;
        }
    });

    final HttpResponse httpRes = HttpHelper.doGet(httpClient, url, null);

    return httpRes.getStatusLine().getStatusCode();
}