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

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

Introduction

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

Prototype

@Override
public void setFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)

Usage

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);/*  www .j  a  v  a2 s .  c  o m*/
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.deri.pipes.utils.HttpResponseCache.java

private static HttpResponseData getDataFromRequest(HttpClient client, String location,
        Map<String, String> requestHeaders) throws IOException, HttpException {
    HttpMethodBase method = new GetMethod(location);
    method.setFollowRedirects(true);
    try {/*from  w ww.  ja v  a2s .com*/
        if (location.length() > 2000 && location.indexOf('?') >= 0) {
            logger.info("Using post method because request location is very long");
            PostMethod postMethod = new PostMethod(location.substring(0, location.indexOf('?')));
            String urlDecoded = URLDecoder.decode(location.substring(location.indexOf('?') + 1), "UTF-8");
            String[] parts = urlDecoded.split("\\&");
            for (String part : parts) {
                String[] keyval = part.split("=", 2);
                if (keyval.length == 2) {
                    postMethod.addParameter(keyval[0], keyval[1]);
                } else {
                    postMethod.addParameter(keyval[0], "");
                }
            }
            method = postMethod;
        }
        addRequestHeaders(method, requestHeaders);
        int response = client.executeMethod(method);
        HttpResponseData data = new HttpResponseData();
        setExpires(data, method);
        data.setResponse(response);
        data.setCharSet(method.getResponseCharSet());
        Header lastModifiedHeader = method.getResponseHeader(HEADER_LAST_MODIFIED);
        if (lastModifiedHeader != null) {
            data.setLastModified(lastModifiedHeader.getValue());
        }
        Header contentTypeHeader = method.getResponseHeader(HEADER_CONTENT_TYPE);
        if (contentTypeHeader != null) {
            data.setContentType(contentTypeHeader.getValue());
        }
        data.setBody(method.getResponseBody(MAX_CONTENT_SIZE));

        return data;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Sets the http parameters.// w  ww .j av a2 s.  co  m
 * 
 * @param http
 *          the http
 * @param httpMethod
 *          the http method
 */
private void setHttpParameters(HttpBase http, HttpMethodBase httpMethod) {
    httpMethod.setFollowRedirects(false);
    httpMethod.setRequestHeader("User-Agent", http.getUserAgent());
    httpMethod.setRequestHeader("Referer", http.getReferer());

    httpMethod.setDoAuthentication(true);

    for (Header header : http.getHeaders()) {
        httpMethod.addRequestHeader(header);
    }

    final HttpMethodParams params = httpMethod.getParams();
    if (http.getUseHttp11()) {
        params.setVersion(HttpVersion.HTTP_1_1);
    } else {
        params.setVersion(HttpVersion.HTTP_1_0);
    }
    params.makeLenient();
    params.setContentCharset("UTF-8");

    if (http.isCookiesEnabled()) {
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    } else {
        params.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }
    params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    // the default is to retry 3 times; if
    // the request body was sent the method is not retried, so there is
    // little danger in retrying
    // retries are handled on the higher level
    params.setParameter(HttpMethodParams.RETRY_HANDLER, null);
}

From source file:org.httpobjects.proxy.Proxy.java

protected Response proxyRequest(Request req, final HttpMethodBase method) {
    method.setFollowRedirects(false);

    String path = req.path().valueFor("path");
    if (!path.startsWith("/"))
        path = "/" + path;
    String query = getQuery(req);
    if (query == null) {
        query = "";
    } else {/*from   w  w w.  j  av  a 2 s.co m*/
        query = "?" + query;
    }
    String url = base + path + query;
    log.debug("doing a " + method.getClass().getSimpleName() + " for " + url);
    //      log.debug("Content type is " + req.representation().contentType());
    try {
        method.setURI(new URI(processUrl(url), true));
    } catch (URIException e1) {
        throw new RuntimeException("Error with uri: " + url, e1);
    }

    addRequestHeaders(req, method);

    if (req.representation().contentType() != null) {
        method.addRequestHeader("Content-Type", req.representation().contentType());
    }

    for (Header next : method.getRequestHeaders()) {
        log.debug("Sending header: " + next);
    }

    HttpClient client = createHttpClient();

    return executeMethod(client, method, req);

}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req//from   w ww.ja v a  2 s .  c  o m
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:org.pentaho.pac.server.common.ThreadSafeHttpClient.java

/**
 * /*from  w  ww. j  av  a  2 s .  co m*/
 * @param serviceName String can be null or empty string.
 * @param mapParams
 * @param requestedMimeType
 * @return
 * @throws ProxyException  ProxyException if the attempt to communicate with the server fails,
 * if the attempt to read the response from the server fails, if the response
 * stream is unable to be converted into a String.
 */
public String execRemoteMethod(String baseUrl, String serviceName, HttpMethodType methodType,
        Map<String, Object> mapParams, String requestedMimeType) throws ProxyException {

    assert null != baseUrl : "baseUrl cannot be null"; //$NON-NLS-1$

    String serviceUrl = baseUrl;
    if (!StringUtils.isEmpty(serviceName)) {
        if (!serviceUrl.endsWith("/")) { //$NON-NLS-1$
            serviceUrl = serviceUrl + "/"; //$NON-NLS-1$
        }
        serviceUrl = serviceUrl + serviceName;
    }
    if (null == mapParams) {
        mapParams = new HashMap<String, Object>();
    }
    mapParams.put(REQUESTED_MIME_TYPE, requestedMimeType);

    HttpMethodBase method = null;
    switch (methodType) {
    case POST:
        method = new PostMethod(serviceUrl);
        method.getParams().setContentCharset(contentCharacterSet);//$NON-NLS-1$
        setPostMethodParams((PostMethod) method, mapParams);
        method.setFollowRedirects(false);
        break;
    case GET:
        method = new GetMethod(serviceUrl);
        method.getParams().setContentCharset(contentCharacterSet); //$NON-NLS-1$  
        setGetMethodParams((GetMethod) method, mapParams);
        method.setFollowRedirects(true);
        break;
    default:
        throw new RuntimeException(Messages.getErrorString(
                "ThreadSafeHttpClient.ERROR_0002_INVALID_HTTP_METHOD_TYPE", methodType.toString())); // can never happen //$NON-NLS-1$
    }
    return executeMethod(method);
}

From source file:org.rhq.enterprise.server.plugins.url.HttpProvider.java

/**
 * Given a client and the method to be used by that client, this will prepare those objects
 * so they can be used to get the remote content.
 * //from   w ww .j  a  v a2s  . c om
 * @param client
 * @param method
 * 
 * @throws Exception if the client cannot be prepared successfully
 */
protected void prepareHttpClient(HttpClient client, HttpMethodBase method) throws Exception {

    // prepare the client with proxy info, if appropriate
    configureProxy(client);

    // setup the authentication
    method.setFollowRedirects(true);

    if (this.username != null) {
        method.setDoAuthentication(true);

        org.apache.commons.httpclient.URI fullUri = method.getURI();
        AuthScope authScope = new AuthScope(fullUri.getHost(), fullUri.getPort(), AuthScope.ANY_REALM);
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        client.getState().setCredentials(authScope, credentials);
    }

    return;
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private HttpMethodBase initConnection(URI link, Map<Object, Object> properties) throws IOException {

    /* Create the Method. Wrap any RuntimeException into an IOException */
    HttpMethodBase method = null;
    try {/* w w  w  .j a  v  a 2s .c o  m*/
        if (properties != null && properties.containsKey(IConnectionPropertyConstants.POST))
            method = new PostMethod(link.toString());
        else
            method = new GetMethod(link.toString());
    } catch (RuntimeException e) {
        throw new IOException(e.getMessage());
    }

    /* Ignore Cookies */
    if (method instanceof GetMethod)
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

    /* Set Headers */
    setHeaders(properties, method);

    /* Set Parameters (POST only) */
    if (method instanceof PostMethod && properties != null
            && properties.containsKey(IConnectionPropertyConstants.PARAMETERS)) {
        Map<?, ?> parameters = (Map<?, ?>) properties.get(IConnectionPropertyConstants.PARAMETERS);
        Set<?> entries = parameters.entrySet();
        for (Object obj : entries) {
            Entry<?, ?> entry = (Entry<?, ?>) obj;
            String key = (String) entry.getKey();
            if (entry.getValue() instanceof String)
                ((PostMethod) method).addParameter(key, (String) entry.getValue());
            else if (entry.getValue() instanceof String[]) {
                String[] parameterValues = (String[]) entry.getValue();
                for (String value : parameterValues) {
                    ((PostMethod) method).addParameter(key, value);
                }
            }
        }
    }

    /* Follow Redirects */
    if (method instanceof GetMethod)
        method.setFollowRedirects(true);

    return method;
}

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

protected <T extends Object> T executeMethod(HttpMethodBase method, IRedmineResponseParser<T> parser,
        IProgressMonitor monitor, int... expectedSC) throws RedmineException {
    monitor = Policy.monitorFor(monitor);
    method.setFollowRedirects(false);
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    T response = null;/*w w w .  j av  a 2s  . c o m*/
    try {
        int sc = executeMethod(method, hostConfiguration, monitor);

        if (parser != null && expectedSC != null) {
            boolean found = false;
            for (int i : expectedSC) {
                if (i == sc) {
                    InputStream input = WebUtil.getResponseBodyAsStream(method, monitor);
                    try {
                        found = true;
                        response = parser.parseResponse(input, sc);
                    } finally {
                        input.close();
                    }
                    break;
                }
            }
            if (!found) {
                String msg = Messages.AbstractRedmineClient_UNEXPECTED_RESPONSE_CODE;
                msg = String.format(msg, sc, method.getPath(), method.getName());
                IStatus status = new Status(IStatus.ERROR, RedmineCorePlugin.PLUGIN_ID, msg);
                StatusHandler.fail(status);
                throw new RedmineStatusException(status);
            }
        }
    } catch (RedmineErrorException e) {
        IStatus status = RedmineCorePlugin.toStatus(e, null);
        StatusHandler.fail(status);
        throw new RedmineStatusException(status);
    } catch (IOException e) {
        IStatus status = RedmineCorePlugin.toStatus(e, null);
        StatusHandler.log(status);
        throw new RedmineStatusException(status);
    } finally {
        method.releaseConnection();
    }

    return response;
}