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

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

Introduction

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

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:org.jboss.test.web.test.EncXmlUnitTestCase.java

/** Access the http://{host}/simple-xmlonly/ENCServlet
 *///  w w w  .ja va 2s  . c o m
public void testAltRequestInfoServlet() throws Exception {
    URL url = new URL(baseURL + "simple-xmlonly/ENCServlet");
    HttpMethodBase request = HttpUtils.accessURL(url);
    Header errors = request.getResponseHeader("X-Exception");
    log.info("X-Exception: " + errors);
    assertTrue("X-Exception(" + errors + ") is null", errors == null);
}

From source file:org.jboss.test.web.test.UserInRoleUnitTestCase.java

/**
 * Test that two wars from different security domains with common principal
 * names do not conflict in terms of isUserInRole results.
 * http://jira.jboss.com/jira/browse/JBAS-3043
 * /*from  w w w.  j  a v a  2 s  .  c o m*/
 * This is the non-jacc version where the programmatic security of isUserInRole
 * will work off of the roles populated in the subject, irrespective of whether
 * the roles are fully defined in the web.xml
 * @throws Exception
 */
public void testConflictingUserInRole() throws Exception {
    if (jacc == Boolean.TRUE)
        return;
    log.info("+++ testConflictingUserInRole");
    String base = HttpUtils.getBaseURL("sa", "sa");

    // Hit the first web app and validate isUserInRole calls
    URL url1 = new URL(base + "userinrole1");
    HttpMethodBase request = HttpUtils.accessURL(url1, "JBAS-3043-1", HttpURLConnection.HTTP_OK);
    Header X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is true", "true", X.getValue());
    Header Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is false", "false", Y.getValue());
    Header Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());

    // Hit the second web app and validate isUserInRole calls
    URL url2 = new URL(base + "userinrole2");
    request = HttpUtils.accessURL(url2, "JBAS-3043-2", HttpURLConnection.HTTP_OK);
    X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is false", "false", X.getValue());
    Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is true", "true", Y.getValue());
    Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());

    request = HttpUtils.accessURL(url1, "JBAS-3043-1", HttpURLConnection.HTTP_OK);
    X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is true", "true", X.getValue());
    Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is false", "false", Y.getValue());
    Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());
}

From source file:org.jboss.test.web.test.UserInRoleUnitTestCase.java

/**
 * Test that two wars from different security domains with common principal
 * names do not conflict in terms of isUserInRole results.
 * http://jira.jboss.com/jira/browse/JBAS-3043 
 * // w  w w.j av  a 2  s .  co m
 * This is the jacc version where the programmatic security of isUserInRole
 * will work only of the roles are fully defined in the web.xml
 * @throws Exception
 */
public void testConflictingUserInRoleJaccVersion() throws Exception {
    if (jacc == Boolean.FALSE)
        return;
    log.info("+++ testConflictingUserInRole");
    String base = HttpUtils.getBaseURL("sa", "sa");

    // Hit the first web app and validate isUserInRole calls
    URL url1 = new URL(base + "userinrole1");
    HttpMethodBase request = HttpUtils.accessURL(url1, "JBAS-3043-1", HttpURLConnection.HTTP_OK);
    Header X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is false", "false", X.getValue());
    Header Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is false", "false", Y.getValue());
    Header Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());

    // Hit the second web app and validate isUserInRole calls
    URL url2 = new URL(base + "userinrole2");
    request = HttpUtils.accessURL(url2, "JBAS-3043-2", HttpURLConnection.HTTP_OK);
    X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is false", "false", X.getValue());
    Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is false", "false", Y.getValue());
    Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());

    request = HttpUtils.accessURL(url1, "JBAS-3043-1", HttpURLConnection.HTTP_OK);
    X = request.getResponseHeader("X-isUserInRole-X");
    log.info("X " + X);
    assertEquals("X-isUserInRole-X(" + X + ") is false", "false", X.getValue());
    Y = request.getResponseHeader("X-isUserInRole-Y");
    log.info("Y " + Y);
    assertEquals("X-isUserInRole-Y(" + Y + ") is false", "false", Y.getValue());
    Z = request.getResponseHeader("X-isUserInRole-Z");
    log.info("Z " + Z);
    assertEquals("X-isUserInRole-Z(" + Z + ") is true", "true", Z.getValue());
}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** Access the http://{host}/jbosstest/restricted/UserInRoleServlet to
 * test isUserInRole.//w w  w.  j av a 2s .co m
 */
public void testUserInRoleServlet() throws Exception {
    URL url = new URL(baseURL + "jbosstest/restricted/UserInRoleServlet");
    HttpMethodBase request = HttpUtils.accessURL(url);
    Header errors = request.getResponseHeader("X-ExpectedUserRoles-Errors");
    log.info("X-ExpectedUserRoles-Errors: " + errors);
    assertTrue("X-ExpectedUserRoles-Errors(" + errors + ") is null", errors == null);
    errors = request.getResponseHeader("X-UnexpectedUserRoles-Errors");
    log.info("X-UnexpectedUserRoles-Errors: " + errors);
    assertTrue("X-UnexpectedUserRoles-Errors(" + errors + ") is null", errors == null);
}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** Access the http://{host}/jbosstest/restricted/SubjectServlet
 *//*from  w  ww  .j av  a2s . com*/
public void testSubjectServlet() throws Exception {
    URL url = new URL(baseURL + "jbosstest/restricted/SubjectServlet");
    HttpMethodBase request = HttpUtils.accessURL(url);
    Header hdr = request.getResponseHeader("X-SubjectServlet");
    log.info("X-SubjectServlet: " + hdr);
    assertTrue("X-SubjectServlet(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-SubjectFilter-ENC");
    log.info("X-SubjectFilter-ENC: " + hdr);
    assertTrue("X-SubjectFilter-ENC(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-SubjectFilter-SubjectSecurityManager");
    log.info("X-SubjectFilter-SubjectSecurityManager: " + hdr);
    assertTrue("X-SubjectFilter-SubjectSecurityManager(" + hdr + ") is NOT null", hdr != null);
}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** Test of a war that accesses classes referred to via the war manifest
 * classpath. Access the http://{host}/manifest/classpath.jsp
 *///from w  w  w. ja  v a 2  s .  c  o m
public void testWarManifest() throws Exception {
    deploy("manifest-web.ear");
    try {
        String baseURL = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + '/';
        URL url = new URL(baseURL + "manifest/classpath.jsp");
        HttpMethodBase request = HttpUtils.accessURL(url);
        Header errors = request.getResponseHeader("X-Exception");
        log.info("X-Exception: " + errors);
        assertTrue("X-Exception(" + errors + ") is null", errors == null);
    } finally {
        undeploy("manifest-web.ear");
    }
}

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

/**
 * @param since last modified time to use
 * @param req//from w w w  .  j a va  2 s.com
 * @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.opentides.util.UrlUtil.java

/**
 * Returns the HTML code of the original engine. Takes the URL to connect to
 * the engine. Also takes encoding type that overrides default if not null
 * "UTF8" is typical encoding type/*ww  w.jav a  2  s.  c  o m*/
 * 
 * @param queryURL
 *            - URL of engine to retrieve
 * @param request
 *            - request object
 * @param param
 *            - additional parameters
 *              - Valid parameters are:
 *              - methodName - Either "POST" or "GET". Default is "POST"   
 *            - forwardCookie - if true, will forward cookies found on request object
 *            - IPAddress - if specified, this IP will be used for the request
 *        
 */
public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request,
        final Map<String, Object> param) {
    // determine if get or post method
    HttpMethodBase httpMethodBase;
    Boolean forwardCookie = false;
    InetAddress IPAddress = null;

    if (param != null) {
        if (param.get("forwardCookie") != null)
            forwardCookie = (Boolean) param.get("forwardCookie");

        if (param.get("IPAddress") != null) {
            String IPString = (String) param.get("IPAddress");
            if (!StringUtil.isEmpty(IPString)) {
                IPAddress = convertIPString(IPString);
            }
        }
    }

    if (param != null && "GET".equals((String) param.get("methodName"))) {
        httpMethodBase = new GetMethod(queryURL);
    } else {
        httpMethodBase = new PostMethod(queryURL);
    }

    try {
        // declare the connection objects
        HttpClient client = new HttpClient();
        HostConfiguration hostConfig = new HostConfiguration();
        String userAgent = request.getHeader("User-Agent");

        // for debugging
        if (_log.isDebugEnabled())
            _log.debug("Retrieving page from " + queryURL);

        // initialize the connection settings
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
        client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        httpMethodBase.addRequestHeader("accept", "*/*");
        httpMethodBase.addRequestHeader("accept-language", "en-us");
        httpMethodBase.addRequestHeader("user-agent", userAgent);

        if (forwardCookie) {
            // get cookies from request
            Cookie[] cookies = request.getCookies();
            String cookieString = "";
            for (Cookie c : cookies) {
                cookieString += c.getName() + "=" + c.getValue() + "; ";
            }

            // forward cookies to httpMethod
            httpMethodBase.setRequestHeader("Cookie", cookieString);
        }

        if (IPAddress != null) {
            hostConfig.setLocalAddress(IPAddress);
        }

        // Setup for 3 retry  
        httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        // now let's retrieve the data
        client.executeMethod(hostConfig, httpMethodBase);

        // Read the response body.
        UrlResponseObject response = new UrlResponseObject();
        response.setResponseBody(httpMethodBase.getResponseBody());
        Header contentType = httpMethodBase.getResponseHeader("Content-Type");
        if (contentType != null)
            response.setResponseType(contentType.getValue());
        else
            response.setResponseType(Widget.TYPE_HTML);
        return response;

    } catch (Exception ex) {
        _log.error("Failed to request from URL: [" + queryURL + "]", ex);
        return null;
    } finally {
        try {
            httpMethodBase.releaseConnection();
        } catch (Exception ignored) {
        }
    }
}

From source file:org.opentides.util.WidgetUtil.java

/**
 * Returns the HTML code of the original engine. Takes the URL to connect to
 * the engine. Also takes encoding type that overrides default if not null
 * "UTF8" is typical encoding type//from  w  ww  .j a v a2  s  .  c  o m
 * 
 * @param queryURL
 *            - URL of engine to retrieve
 * @param request
 *            - request object
 * @param param
 *            - additional parameters
 *              - Valid parameters are:
 *              - methodName - Either "POST" or "GET". Default is "POST"   
 *            - forwardCookie - if true, will forward cookies found on request object
 *            - IPAddress - if specified, this IP will be used for the request
 *        
 */
public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request,
        final Map<String, Object> param) {
    // determine if get or post method
    HttpMethodBase httpMethodBase;
    Boolean forwardCookie = false;
    InetAddress IPAddress = null;

    if (param != null) {
        if (param.get("forwardCookie") != null)
            forwardCookie = (Boolean) param.get("forwardCookie");

        if (param.get("IPAddress") != null) {
            String IPString = (String) param.get("IPAddress");
            if (!StringUtil.isEmpty(IPString)) {
                IPAddress = UrlUtil.convertIPString(IPString);
            }
        }
    }

    if (param != null && "GET".equals((String) param.get("methodName"))) {
        httpMethodBase = new GetMethod(queryURL);
    } else {
        httpMethodBase = new PostMethod(queryURL);
    }

    try {
        // declare the connection objects
        HttpClient client = new HttpClient();
        HostConfiguration hostConfig = new HostConfiguration();
        String userAgent = request.getHeader("User-Agent");

        // for debugging
        if (_log.isDebugEnabled())
            _log.debug("Retrieving page from " + queryURL);

        // initialize the connection settings
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
        client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        httpMethodBase.addRequestHeader("accept", "*/*");
        httpMethodBase.addRequestHeader("accept-language", "en-us");
        httpMethodBase.addRequestHeader("user-agent", userAgent);

        if (forwardCookie) {
            // get cookies from request
            Cookie[] cookies = request.getCookies();
            String cookieString = "";
            for (Cookie c : cookies) {
                cookieString += c.getName() + "=" + c.getValue() + "; ";
            }

            // forward cookies to httpMethod
            httpMethodBase.setRequestHeader("Cookie", cookieString);
        }

        if (IPAddress != null) {
            hostConfig.setLocalAddress(IPAddress);
        }

        // Setup for 3 retry  
        httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        // now let's retrieve the data
        client.executeMethod(hostConfig, httpMethodBase);

        // Read the response body.
        UrlResponseObject response = new UrlResponseObject();
        response.setResponseBody(httpMethodBase.getResponseBody());
        Header contentType = httpMethodBase.getResponseHeader("Content-Type");
        if (contentType != null)
            response.setResponseType(contentType.getValue());
        else
            response.setResponseType("html");
        return response;

    } catch (Exception ex) {
        _log.error("Failed to request from URL: [" + queryURL + "]", ex);
        return null;
    } finally {
        try {
            httpMethodBase.releaseConnection();
        } catch (Exception ignored) {
        }
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

/**
 * @param response/*w  w w . j ava  2  s  .  c  om*/
 * @param bridgeRequest
 * @param perPortletMemento
 * @param url
 * @throws ServletException
 */
protected void fetch(final HttpServletRequest request, final HttpServletResponse response,
        final BridgeRequest bridgeRequest, final PortletBridgeMemento memento,
        final PerPortletMemento perPortletMemento, final URI url) throws ServletException {
    try {
        GetMethod getMethod = new GetMethod(url.toString());
        // TODO: suspect to send the same request headers after a redirect?
        copyRequestHeaders(request, getMethod);
        httpClientTemplate.service(getMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    org.apache.commons.httpclient.URI effectiveUri = method.getURI();
                    BridgeRequest effectiveBridgeRequest = null;
                    if (!effectiveUri.toString().equals(url.toString())) {
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        effectiveBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), new URI(effectiveUri.toString()));
                    } else {
                        effectiveBridgeRequest = bridgeRequest;
                    }
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(effectiveBridgeRequest.getId(),
                                new PortletBridgeContent(url, "get", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end
                        response.sendRedirect(effectiveBridgeRequest.getPageUrl());
                    } else if (responseHeader != null
                            && responseHeader.getValue().startsWith("text/javascript")) {
                        // rewrite external javascript
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/javascript");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.script(null, content));
                        writer.flush();
                    } else if (responseHeader != null && responseHeader.getValue().startsWith("text/css")) {
                        // rewrite external css
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/css");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.style(null, content));
                        writer.flush();
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        Header header = method.getResponseHeader("Content-Type");
                        response.setContentType(((null == header.getName() ? "" : header.getName()) + ": "
                                + (null == header.getValue() ? "" : header.getValue())));

                        log.trace("fetch(): returning URL=" + url + ", as stream, content type=" + header);
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}