Example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects

List of usage examples for org.apache.commons.httpclient HttpMethod setFollowRedirects

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects.

Prototype

public abstract void setFollowRedirects(boolean paramBoolean);

Source Link

Usage

From source file:net.oauth.client.OAuthHttpClient.java

/** Send a message to the service provider and get the response. */
@Override//from   w w w.ja  va 2s  .  c o m
protected OAuthMessage invoke(OAuthMessage message) throws Exception {
    String form = OAuth.formEncode(message.getParameters());
    HttpMethod method;
    if ("GET".equals(message.httpMethod)) {
        method = new GetMethod(message.URL);
        method.setQueryString(form);
        // method.addRequestHeader("Authorization", message
        // .getAuthorizationHeader(serviceProvider.userAuthorizationURL));
        method.setFollowRedirects(false);
    } else {
        PostMethod post = new PostMethod(message.URL);
        post.setRequestEntity(new StringRequestEntity(form, OAuth.FORM_ENCODED, null));
        method = post;
    }
    clientPool.getHttpClient(new URL(method.getURI().toString())).executeMethod(method);
    final OAuthMessage response = new HttpMethodResponse(method);
    int statusCode = method.getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        Map<String, Object> dump = response.getDump();
        OAuthProblemException problem = new OAuthProblemException(
                (String) dump.get(OAuthProblemException.OAUTH_PROBLEM));
        problem.getParameters().putAll(dump);
        throw problem;
    }
    return response;
}

From source file:eu.alefzero.webdav.WebdavClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    boolean customRedirectionNeeded = false;
    try {//from   w  w w.ja  va2 s  . co m
        method.setFollowRedirects(mFollowRedirects);
    } catch (Exception e) {
        if (mFollowRedirects)
            Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName()
                    + " method, custom redirection will be used");
        customRedirectionNeeded = mFollowRedirects;
    }
    if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
        method.setRequestHeader("Cookie", mSsoSessionCookie);
    }
    int status = super.executeMethod(method);
    int redirectionsCount = 0;
    while (customRedirectionNeeded && redirectionsCount < MAX_REDIRECTIONS_COUNT
            && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY
                    || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location != null) {
            Log_OC.d(TAG, "Location to redirect: " + location.getValue());
            method.setURI(new URI(location.getValue(), true));
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }

    return status;
}

From source file:mitm.common.security.crl.HTTPCRLDownloadHandler.java

private Collection<? extends CRL> downloadCRLs(URI uri, TaskScheduler watchdog)
        throws IOException, HttpException, CRLException, FileNotFoundException {
    Collection<? extends CRL> crls = null;

    HttpClient httpClient = new HttpClient();

    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();

    params.setConnectionTimeout((int) downloadParameters.getConnectTimeout());
    params.setSoTimeout((int) downloadParameters.getReadTimeout());

    if (proxyInjector != null) {
        try {//  w w w  .  j  av a 2 s.  c  om
            proxyInjector.setProxy(httpClient);
        } catch (ProxyException e) {
            throw new IOException(e);
        }
    }

    HttpMethod getMethod = new GetMethod(uri.toString());

    getMethod.setFollowRedirects(true);
    getMethod.setRequestHeader("User-Agent", NetUtils.HTTP_USER_AGENT);

    /* 
     * Add watchdog that will interrupt the thread on timeout. we want the abort to fire first so add 50% 
     */
    Task threadWatchdogTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName());
    watchdog.addTask(threadWatchdogTask, (long) (downloadParameters.getTotalTimeout() * 1.5));

    /* 
     * Add watchdog that will abort the HTTPMethod on timeout. we want to close the input first so add 20% 
     */
    Task httpMethodAbortTimeoutTask = new HTTPMethodAbortTimeoutTask(getMethod, watchdog.getName());
    watchdog.addTask(httpMethodAbortTimeoutTask, (long) (downloadParameters.getTotalTimeout() * 1.2));

    try {
        logger.debug("Setting up a connection to: " + uri);

        int statusCode = 0;

        try {
            statusCode = httpClient.executeMethod(getMethod);
        } catch (IllegalArgumentException e) {
            /* 
             * HttpClient can throw IllegalArgumentException when the host is not set 
             */
            throw new CRLException(e);
        }

        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("Error getting CRL. Message: " + getMethod.getStatusLine());
        }

        InputStream urlStream = getMethod.getResponseBodyAsStream();

        if (urlStream == null) {
            throw new IOException("Response body is null.");
        }

        /* 
         * add a timeout watchdog on the input 
         */
        Task inputWatchdogTask = new InputStreamTimeoutTask(urlStream, watchdog.getName());

        watchdog.addTask(inputWatchdogTask, downloadParameters.getTotalTimeout());

        /*
         * we want to set a max on the number of bytes to download. We do not want
         * a rogue server to provide us with a 1 TB CRL.
         */
        InputStream limitInputStream = new SizeLimitedInputStream(urlStream, downloadParameters.getMaxBytes());

        ReadableOutputStreamBuffer output = new ReadableOutputStreamBuffer(memThreshold);

        try {
            IOUtils.copy(limitInputStream, output);

            if (threadWatchdogTask.hasRun() || httpMethodAbortTimeoutTask.hasRun()
                    || inputWatchdogTask.hasRun()) {
                /* a timeout has occurred */
                throw new IOException(TIMEOUT_ERROR + uri);
            }

            try {
                InputStream input = output.getInputStream();

                try {
                    crls = CRLUtils.readCRLs(input);
                } finally {
                    IOUtils.closeQuietly(input);
                }

                if (crls == null || crls.size() == 0) {
                    logger.debug("No CRLs found in the downloaded stream.");
                }
            } catch (CertificateException e) {
                throw new CRLException(e);
            } catch (NoSuchProviderException e) {
                throw new CRLException(e);
            } catch (SecurityFactoryFactoryException e) {
                throw new CRLException(e);
            }
        } finally {
            /* 
             * we need to close ReadableOutputStreamBuffer to prevent temp file leak 
             */
            IOUtils.closeQuietly(output);
        }
    } finally {
        getMethod.releaseConnection();
    }

    return crls;
}

From source file:net.sourceforge.eclipsetrader.yahoo.HistoryFeed.java

public void updateHistory(Security security, int interval) {
    if (interval == IHistoryFeed.INTERVAL_DAILY) {
        Calendar from = Calendar.getInstance();
        Calendar to = Calendar.getInstance();

        History history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {/*from w ww  .  j a  va 2 s.com*/
            Bar cd = history.getLast();
            if (cd != null) {
                from.setTime(cd.getDate());
                from.add(Calendar.DATE, 1);
            }
        }

        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            String host = "ichart.finance.yahoo.com"; //$NON-NLS-1$
            BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
            ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
            if (reference != null) {
                IProxyService proxy = (IProxyService) context.getService(reference);
                IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
                if (data != null) {
                    if (data.getHost() != null)
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    if (data.isRequiresAuthentication())
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                }
            }

            String symbol = null;
            if (security.getHistoryFeed() != null)
                symbol = security.getHistoryFeed().getSymbol();
            if (symbol == null || symbol.length() == 0)
                symbol = security.getCode();

            // If the last bar from the data is from a date before today, then
            // download the historical data, otherwise it's enough to download the data for today.
            to.add(Calendar.DAY_OF_MONTH, -1);
            to.set(Calendar.HOUR, 0);
            to.set(Calendar.MINUTE, 0);
            to.set(Calendar.SECOND, 0);
            to.set(Calendar.MILLISECOND, 0);
            Bar lastHistoryBar = history.getLast();
            Date lastDate;
            if (lastHistoryBar == null)
                lastDate = from.getTime();
            else
                lastDate = lastHistoryBar.getDate();
            if (lastDate.before(to.getTime())) {
                log.info("Updating historical data for " + security.getCode() + " - " //$NON-NLS-1$//$NON-NLS-2$
                        + security.getDescription());

                StringBuffer url = new StringBuffer("http://" + host + "/table.csv" + "?s="); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                url.append(symbol);
                url.append("&d=" + to.get(Calendar.MONTH) + "&e=" + to.get(Calendar.DAY_OF_MONTH) + "&f=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + to.get(Calendar.YEAR));
                url.append("&g=d"); //$NON-NLS-1$
                url.append("&a=" + from.get(Calendar.MONTH) + "&b=" + from.get(Calendar.DAY_OF_MONTH) + "&c=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + from.get(Calendar.YEAR));
                url.append("&ignore=.csv"); //$NON-NLS-1$
                log.debug(url);

                HttpMethod method = new GetMethod(url.toString());
                method.setFollowRedirects(true);
                client.executeMethod(method);

                BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

                // The first line is the header, ignoring
                String inputLine = in.readLine();
                log.trace(inputLine);

                while ((inputLine = in.readLine()) != null) {
                    log.trace(inputLine);
                    if (inputLine.startsWith("<")) //$NON-NLS-1$
                        continue;
                    String[] item = inputLine.split(","); //$NON-NLS-1$
                    if (item.length < 6)
                        continue;

                    Calendar day = Calendar.getInstance();
                    try {
                        day.setTime(df.parse(item[0]));
                    } catch (Exception e) {
                        try {
                            day.setTime(dfAlt.parse(item[0]));
                        } catch (Exception e1) {
                            log.error(e1, e1);
                        }
                    }
                    day.set(Calendar.HOUR, 0);
                    day.set(Calendar.MINUTE, 0);
                    day.set(Calendar.SECOND, 0);
                    day.set(Calendar.MILLISECOND, 0);

                    Bar bar = new Bar();
                    bar.setDate(day.getTime());
                    bar.setOpen(Double.parseDouble(item[1].replace(',', '.')));
                    bar.setHigh(Double.parseDouble(item[2].replace(',', '.')));
                    bar.setLow(Double.parseDouble(item[3].replace(',', '.')));
                    bar.setClose(Double.parseDouble(item[4].replace(',', '.')));
                    bar.setVolume(Long.parseLong(item[5]));

                    // Remove the old bar, if exists
                    int index = history.indexOf(bar.getDate());
                    if (index != -1)
                        history.remove(index);

                    history.add(bar);
                }
                in.close();
            }

            // Get the data for today (to-date) using a different URL at Yahoo!
            //Bar lastbar = history.getLast
            log.debug("Get data for today using a separate URL..."); //$NON-NLS-1$
            StringBuffer url = new StringBuffer(
                    "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug(url);

            HttpMethod method = new GetMethod(url.toString());
            method.setFollowRedirects(true);
            client.executeMethod(method);

            BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String inputLine = in.readLine();
            log.trace(inputLine);
            String[] item = inputLine.split(","); //$NON-NLS-1$
            item[2] = item[2].replace("\"", ""); //$NON-NLS-1$ //$NON-NLS-2$

            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //$NON-NLS-1$
            Calendar day = Calendar.getInstance();

            // Transfer the data from the string array to the Bar
            day.setTime(df.parse(item[2]));
            Bar bar = new Bar();
            bar.setDate(day.getTime());
            bar.setOpen(Double.parseDouble(item[5]));
            bar.setClose(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[6]));
            bar.setLow(Double.parseDouble(item[7]));
            bar.setVolume(Long.parseLong(item[8]));

            // Remove the old bar, if exists
            int index = history.indexOf(bar.getDate());
            if (index != -1)
                history.remove(index);
            history.add(bar);

            in.close();

        } catch (Exception e) {
            log.error(e, e);
        }

        CorePlugin.getRepository().save(history);
    } else
        log.warn("Intraday data not supported for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Prepares a HttpMethod object.//from  w  w  w .  ja va 2 s .com
 *
 * @param method The object which gets prepared to access the file object.
 * @throws FileSystemException if an error occurs.
 * @throws URIException if path cannot be represented.
 * @since 2.0 (was package)
 */
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", this.getUserAgent());
}

From source file:net.sourceforge.eclipsetrader.yahoo.Feed.java

private void update() {
    // Builds the url for quotes download
    String host = "quote.yahoo.com"; //$NON-NLS-1$
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); //$NON-NLS-1$ //$NON-NLS-2$
    for (Iterator iter = map.values().iterator(); iter.hasNext();)
        url = url.append((String) iter.next() + "+"); //$NON-NLS-1$
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap"); //$NON-NLS-1$
    log.debug(url.toString());/*from   w ww  .  j a v a 2s. c  o m*/

    // Read the last prices
    String line = ""; //$NON-NLS-1$
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(","); //$NON-NLS-1$
            if (line.indexOf(";") != -1) //$NON-NLS-1$
                item = line.split(";"); //$NON-NLS-1$

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US); //$NON-NLS-1$
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1) //$NON-NLS-1$
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1) //$NON-NLS-1$
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                log.error(e.getMessage() + ": " + line); //$NON-NLS-1$
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase((String) map.get(security))) {
                    security.setQuote(quote, open, high, low, close);
                }
            }
        }
        in.close();
    } catch (Exception e) {
        log.error(e);
    }
}

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }/*from   w w w  .j a  v  a  2  s  .  c  o m*/
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}

From source file:autohit.call.modules.SimpleHttpModule.java

/**
 * Start method. It will set the target address for the client, as well as
 * clearing any state./* w w w .  j a  va  2s  .c  om*/
 * 
 * @param url
 *            the Url path, not to include protocol, address, and port (ie.
 *            "/goats/index.html").
 * @return the data from the page as a String
 * @throws CallException
 */
private String get(String url) throws CallException {

    if (started == false) {
        throw buildException("module:SimpleHttp:Tried to get when a session wasn't started.",
                CallException.CODE_MODULE_FAULT);
    }

    String result = null;

    // Construct our method.
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);

    //execute the method
    try {
        // Do it
        debug("(get)get=" + url);
        httpClient.executeMethod(method);

        // Process result
        result = method.getResponseBodyAsString();
        log("(get)" + method.getStatusLine().toString() + " size=" + result.length());

    } catch (HttpException he) {
        // Bad but not fatal
        error("(get)Error on connect to url " + url + ".  Error=" + he.getMessage());
    } catch (IOException ioe) {
        // Fatal
        throw buildException("(get)Unable to connect.  Session is invalid.  message=" + ioe.getMessage(),
                CallException.CODE_MODULE_FAULT, ioe);
    } finally {
        try {
            method.releaseConnection();
            method.recycle();
        } catch (Exception e) {
            // Already FUBAR
        }
    }
    return result;
}

From source file:net.kenware.langtrans.GoogleTranslater.java

/**
 * translates source string (sin) into a response using the source/target
 * languages./*from w  w  w  .j  a v  a  2  s  .c  o  m*/
 *
 * @param sin String in
 * @param sourcelang source language (ISO3166 code)
 * @param targetlang target language (ISO3166 code)
 * @return returns a text string in the target language
 */
public String urlTranslate(String sin, String sourcelang, String targetlang) {
    String response = "";
    String url = null;
    HttpClient client = new HttpClient();
    HttpMethod method = null;
    String responsebody = null;

    try {
        String s = URLEncoder.encode(sin, "UTF-8");
        url = "http://google.com/translate_t?hl=en&ie=UTF8&text=" + s + "&langpair=" + sourcelang + "%7C"
                + targetlang;
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        method = new GetMethod(url);
        method.setFollowRedirects(true);

        client.executeMethod(method);
        responsebody = method.getResponseBodyAsString();
        method.releaseConnection();

        response = extractResponse(responsebody);

    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());

    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");

    } catch (Exception ex) {
        System.err.println("EXCEPTION: " + ex.getMessage());
    } // end-try-catch

    return (response);
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *///from  w w  w.  ja v  a 2  s. c  om
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    httpMethodProxyRequest.setFollowRedirects(false);
    String port = "" + httpServletRequest.getSession().getAttribute("civserverport");
    String host = "" + httpServletRequest.getSession().getAttribute("civserverhost");
    String username = "" + httpServletRequest.getSession().getAttribute("username");
    httpMethodProxyRequest.addRequestHeader("civserverport", port);
    httpMethodProxyRequest.addRequestHeader("civserverhost", host);
    httpMethodProxyRequest.addRequestHeader("username", username);
    int intProxyResponseCode = 0;
    // Execute the request
    try {
        intProxyResponseCode = client.executeMethod(httpMethodProxyRequest);
    } catch (IOException ioErr) {
        //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. 
        //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        httpServletResponse.setStatus(502);
        outputStreamClientResponse
                .write("Freeciv web client proxy not responding (most likely died).".getBytes());
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            httpMethodProxyRequest.releaseConnection();
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
        httpMethodProxyRequest.releaseConnection();
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
    int intNextByte;
    while ((intNextByte = bufferedInputStream.read()) != -1) {
        outputStreamClientResponse.write(intNextByte);
    }
    httpMethodProxyRequest.releaseConnection();
}