Example usage for org.apache.http.impl.client DefaultHttpClient setRedirectHandler

List of usage examples for org.apache.http.impl.client DefaultHttpClient setRedirectHandler

Introduction

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

Prototype

@Deprecated
public synchronized void setRedirectHandler(final RedirectHandler handler) 

Source Link

Usage

From source file:com.manning.androidhacks.hack023.net.HttpHelper.java

private static DefaultHttpClient setupHttpClient() {
    HttpParams httpParams = new BasicHttpParams();
    setConnectionParams(httpParams);/*  www.j  a  v a 2  s  .  c  o m*/
    SchemeRegistry schemeRegistry = registerFactories();
    ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams,
            schemeRegistry);

    DefaultHttpClient client = new DefaultHttpClient(clientConnectionManager, httpParams);
    client.setRedirectHandler(new FollowPostRedirectHandler());

    return client;
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

private static HttpClient createHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new RedirectHandler());
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    return httpClient;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout,
        Boolean pRedirect) throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    if (!pRedirect) {
        HttpClientParams.setRedirecting(httpParams, false);
    }/* ww w  . j  av  a 2  s .  c om*/
    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

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

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout)
        throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    HttpClientParams.setRedirecting(httpParams, true);

    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override//w w w.java2  s  . c o m
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketTimeoutException e) {
        e = new SocketTimeoutException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

From source file:org.peterbaldwin.client.android.delicious.WebPageTitleRequest.java

/**
 * {@inheritDoc}//from w  ww.j av  a 2s . co  m
 */
public void run() {
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        client.setRedirectHandler(this);
        try {
            HttpGet request = new HttpGet(mUrl);

            // Set a generic User-Agent to avoid being 
            // redirected to a mobile UI.
            request.addHeader("User-Agent", "Mozilla/5.0");

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
            try {
                int statusCode = statusLine.getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    throw new IOException("Unexpected response code: " + statusCode);
                }

                // Send redirect before checking content type
                // because the redirect is important even if the
                // title cannot be extracted.
                if (mRedirectLocation != null && !mUrl.equals(mRedirectLocation)) {
                    int what = HANDLE_REDIRECT;
                    Object obj = mRedirectLocation;
                    Message msg = mHandler.obtainMessage(what, obj);
                    msg.sendToTarget();
                }
                Header contentType = entity.getContentType();
                if (contentType != null) {
                    String value = contentType.getValue();
                    if (!isHtml(value)) {
                        // This is important because the user might try
                        // bookmarking a video or another large file.
                        throw new IOException("Unsupported content type: " + value);
                    }
                } else {
                    throw new IOException("Content type is missing");
                }
                String source = EntityUtils.toString(entity);
                Html.ImageGetter imageGetter = null;
                Html.TagHandler tagHandler = this;
                Html.fromHtml(source, imageGetter, tagHandler);
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } finally {
            client.getConnectionManager().shutdown();
        }
    } catch (TerminateParser e) {
        // Thrown by handleTag to terminate parser early.
    } catch (IOException e) {
        Log.e(LOG_TAG, "i/o error", e);
    } catch (RuntimeException e) {
        Log.e(LOG_TAG, "runtime error", e);
    } catch (Error e) {
        Log.e(LOG_TAG, "severe error", e);
    } finally {
        Message msg = mHandler.obtainMessage(HANDLE_TITLE, mTitle);
        msg.sendToTarget();
    }
}

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  www. j a  v a  2 s  . co m*/
        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:com.akop.bach.parser.LiveParser.java

@Override
protected DefaultHttpClient createHttpClient(Context context) {
    mLastRedirectedUrl = null;//from   ww  w  .j  ava  2  s . c  om

    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:de.taxilof.UulmLoginAgent.java

/**
 * perform the Login & necessary Checks
 *//*from w w w  .j  a v a 2s .  co m*/
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:at.alladin.rmbt.client.v2.task.HttpProxyTask.java

/**
 * //  www  .  ja v  a 2  s  . 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:se.vgregion.pubsub.push.impl.DefaultPushSubscriber.java

/**
 * {@inheritDoc}//from w w  w  . j a v  a  2  s  .  c om
 */
@Override
public synchronized void publish(Feed feed, PushJms pushJms) throws PublicationFailedException {
    if (active) {
        LOG.info("Getting subscribed feed for {}", callback);
        LOG.debug("Using PushSubcriber {}", this);

        if (feed.hasUpdates(getLastUpdated())) {

            LOG.info("Feed has updates, distributing to {}", callback);
            HttpPost post = new HttpPost(callback);

            post.addHeader(new BasicHeader("Content-Type", feed.getContentType().toString()));

            Document doc = AbstractSerializer.create(feed.getContentType()).print(feed,
                    new MustHaveRequestIdFilter(getLastUpdated()));

            String xml = doc.toXML();

            LOG.debug("XML being pushed to subscriber:");
            LOG.debug(xml);

            post.setEntity(HttpUtil.createEntity(xml));

            if (StringUtils.isNotBlank(secret)) {
                // calculate HMAC header
                post.addHeader(new BasicHeader("X-Hub-Signature",
                        "sha1=" + CryptoUtil.calculateHmacSha1(secret, xml)));
            }
            PushJms localJms = pushJms;
            HttpResponse response = null;
            try {
                DefaultHttpClient httpClient = HttpUtil.getClient();

                // don't redirect publications
                httpClient.setRedirectHandler(new DontRedirectHandler());

                response = httpClient.execute(post);
                LOG.debug("XML has been pushed to subscriber");

                Feed newFeed = AbstractParser.create(ContentType.ATOM).parse(xml, ContentType.ATOM);

                if (localJms != null) {
                    if (getJmsLoggAddress() != null && !"".equals(getJmsLoggAddress())) {
                        localJms = pushJms.copy(getJmsLoggAddress());
                    }
                    localJms.send(newFeed, "event-text", DocumentStatusType.OK);
                }

                if (HttpUtil.successStatus(response)) {
                    LOG.info("Succeeded distributing to subscriber {}", callback);

                    // update last update
                    lastUpdated = new DateTime().getMillis();
                } else {
                    // TODO revisit
                    // subscription.markForVerification();
                    String msg = "Failed distributing to subscriber \"" + callback + "\" with error \""
                            + response.getStatusLine() + "\"";

                    LOG.warn(msg);
                    throw new PublicationFailedException(msg);
                }
                loggedErrorOnLastPush.put(getId(), false);
            } catch (Exception e) {
                // TODO revisit
                //subscription.markForVerification();

                String msg = "Failed distributing to subscriber \"" + callback + "\" with error: ";
                LOG.error(msg);
                if (localJms != null && !loggedErrorOnLastPush.get(getId())) {
                    try {
                        Feed newFeed = AbstractParser.create(ContentType.ATOM).parse(xml, ContentType.ATOM);
                        localJms.send(newFeed, e.getMessage(), DocumentStatusType.ERROR);
                    } catch (Exception e1) {
                        LOG.error("Failed to log errors to jms", e1);
                    }
                }
                loggedErrorOnLastPush.put(getId(), true);

                throw new PublicationFailedException(msg, e);
            } finally {
                HttpUtil.closeQuitely(response);
            }
        } else {
            LOG.info("No updates for subscriber {}", callback);
        }
    } else {
        LOG.debug("Subscriber for {} disabled", callback);
    }
}