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:gov.nih.nci.cagwas.web.action.RemoteContentHelper.java

/**
 * getContent will connect to the passed in address and read in the contents and
 * return them as a String.//  ww  w  .  j a  va2 s .  co  m
 * <P>
 * @param addr The URL address to read the contents from
 * @return String the contents or null if unable to connect
 */
private String getContent(String addr) {
    String responseBody = null;

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    HttpMethod method = new GetMethod(addr);
    method.setFollowRedirects(true);

    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException e) {
        logger.error("Error connecting to remote site", e);
    } catch (IOException e) {
        logger.error("Error connecting to remote site", e);
    }

    return responseBody;
}

From source file:com.trunghoang.teammedical.utils.FileDownloader.java

public File urlDownloader(String downloadLocation) throws Exception {
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.getParams().makeLenient();// www. j av  a 2  s  .c  o  m
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadLocation);
    getRequest.setFollowRedirects(true);
    FileHandler downloadedFile = new FileHandler(
            downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
    try {
        int status = client.executeMethod(getRequest);
        log.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
        downloadedFile.getWritableFileOutputStream().write(getRequest.getResponseBody());
        downloadedFile.close();
        log.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
    } catch (Exception Ex) {
        log.error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getFile();
}

From source file:net.datapipe.CloudStack.CloudStackAPI.java

protected HttpMethod makeHttpGet(LinkedList<NameValuePair> queryValues) throws Exception {
    String query_signature = sign_request(queryValues);
    queryValues.add(new NameValuePair("signature", query_signature));

    HttpMethod method = new GetMethod(apiURL);
    method.setFollowRedirects(true);
    method.setQueryString(queryValues.toArray(new NameValuePair[0]));

    return method;
}

From source file:net.sf.ufsc.http.HttpFile.java

protected void execute(HttpMethod method) throws java.io.IOException {
    method.setFollowRedirects(true);
    method.setDoAuthentication(true);// ww w  .j  av  a  2s . co m

    int status = this.client.executeMethod(method);

    if (status != HttpStatus.SC_OK) {
        throw new java.io.IOException(method.getStatusText());
    }
}

From source file:net.sf.j2ep.ProxyFilter.java

/**
 * Will create the method and execute it. After this the method
 * is sent to a ResponseHandler that is returned.
 * //w  w  w  . ja va2 s . c  o  m
 * @param httpRequest Request we are receiving from the client
 * @param url The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException If the method specified by the request isn't handled
 * @throws IOException When there is a problem with the streams
 * @throws HttpException The httpclient can throw HttpExcetion when executing the method
 */
private ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory.createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException("Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}

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

public void updateHistory(Security security, int interval) {
    History history = null;//from w w w.  ja v a2s  . co  m
    Calendar from = Calendar.getInstance();
    from.set(Calendar.MILLISECOND, 0);

    if (interval < IHistoryFeed.INTERVAL_DAILY) {
        history = security.getIntradayHistory();
        from.set(Calendar.HOUR_OF_DAY, 0);
        from.set(Calendar.MINUTE, 0);
        from.set(Calendar.SECOND, 0);
        log.info("Updating intraday data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {
            Bar cd = history.getLast();
            from.setTime(cd.getDate());
            from.add(Calendar.DATE, 1);
        }
        log.info("Updating historical data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    }

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

    String code = security.getCode();
    if (code.indexOf('.') != -1)
        code = code.substring(0, code.indexOf('.'));

    try {
        String host = "194.185.192.223"; // "grafici.borsaitalia.it";
        StringBuffer url = new StringBuffer(
                "http://" + host + "/scripts/cligipsw.dll?app=tic_d&action=dwnld4push&cod=" + code + "&codneb=" //$NON-NLS-1$//$NON-NLS-2$
                        + symbol + "&req_type=GRAF_DS&ascii=1&form_id=");
        if (interval < IHistoryFeed.INTERVAL_DAILY)
            url.append("&period=1MIN"); //$NON-NLS-1$
        else {
            url.append("&period=1DAY"); //$NON-NLS-1$
            url.append("&From=" + df.format(from.getTime())); //$NON-NLS-1$
        }
        log.debug(url);

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = BorsaitaliaPlugin.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()));

        // 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("@") == true || inputLine.length() == 0) //$NON-NLS-1$
                continue;
            String[] item = inputLine.split("\\|"); //$NON-NLS-1$

            Bar bar = new Bar();
            bar.setDate(df.parse(item[0]));
            bar.setOpen(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[2]));
            bar.setLow(Double.parseDouble(item[3]));
            bar.setClose(Double.parseDouble(item[4]));
            bar.setVolume((long) Double.parseDouble(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();

    } catch (Exception e) {
        CorePlugin.logException(e);
    }

    CorePlugin.getRepository().save(history);
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

private void configureMethod(HttpMethod method, String eid, String sessionId, String csrfNonce) {
    method.setFollowRedirects(false);
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
    method.setQueryString(new NameValuePair[] { new NameValuePair("eid", eid),
            new NameValuePair(REQUEST_PARAMETER_CSRF_NONCE, csrfNonce) });
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException {
    URI targetUri;//from   w ww  .j a  va 2 s . co m
    try {
        targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerVals = request.getHeaders(headerName);
        while (headerVals.hasMoreElements()) {
            String headerValue = headerVals.nextElement();
            headerValue = headerFilter.processRequestHeader(headerName, headerValue);
            if (headerValue != null) {
                commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
            }

        }
    }

    return commonsHttpMethod;
}

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

private int update() {
    int i, requiredDelay = -1;
    String inputLine;//w  w w  . j a v  a2  s .  c o m

    nf.setGroupingUsed(true);
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);

    pf.setGroupingUsed(true);
    pf.setMinimumFractionDigits(4);
    pf.setMaximumFractionDigits(4);

    try {
        // Legge la pagina contenente gli ultimi prezzi
        String host = "registrazioni.directaworld.it";
        StringBuffer url = new StringBuffer("http://" + host + "/cgi-bin/qta?idx=alfa&modo=t&appear=n"); //$NON-NLS-1$
        i = 0;
        for (Iterator iter = map.values().iterator(); iter.hasNext();)
            url.append("&id" + (++i) + "=" + (String) iter.next()); //$NON-NLS-1$ //$NON-NLS-2$
        for (; i < 30; i++)
            url.append("&id" + (i + 1) + "="); //$NON-NLS-1$ //$NON-NLS-2$
        url.append("&u=" + userName + "&p=" + password); //$NON-NLS-1$ //$NON-NLS-2$

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = DirectaWorldPlugin.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 ((inputLine = in.readLine()) != null) {
            if (inputLine.indexOf("<!--QT START HERE-->") != -1) //$NON-NLS-1$
            {
                while ((inputLine = in.readLine()) != null) {
                    if (inputLine.indexOf("<!--QT STOP HERE-->") != -1) //$NON-NLS-1$
                        break;
                    parseLine(inputLine);
                }
            } else if (inputLine.indexOf("Sara' possibile ricaricare la pagina tra") != -1) //$NON-NLS-1$
            {
                int beginIndex = inputLine.indexOf("tra ") + 4; //$NON-NLS-1$
                int endIndex = inputLine.indexOf("sec") - 1; //$NON-NLS-1$
                try {
                    requiredDelay = Integer.parseInt(inputLine.substring(beginIndex, endIndex)) + 1;
                } catch (Exception e) {
                    CorePlugin.logException(e);
                }
            }
        }
        in.close();
    } catch (Exception e) {
        CorePlugin.logException(e);
    }

    return requiredDelay;
}

From source file:com.owncloud.android.oc_framework.network.webdav.WebdavClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    boolean customRedirectionNeeded = false;
    try {//from  ww  w.  ja v  a2  s  .c o  m
        method.setFollowRedirects(mFollowRedirects);
    } catch (Exception e) {
        //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed");
        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.d(TAG, "Location to redirect: " + location.getValue());
            method.setURI(new URI(location.getValue(), true));
            status = super.executeMethod(method);
            redirectionsCount++;

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

    return status;
}