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

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

Introduction

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

Prototype

public abstract String getResponseBodyAsString() throws IOException;

Source Link

Usage

From source file:org.mule.transport.http.functional.HttpKeepAliveFunctionalTestCase.java

private void runHttp11MethodAndAssert(HttpMethod request) throws Exception {
    int status = http11Client.executeMethod(request);
    assertEquals(HttpStatus.SC_OK, status);
    assertEquals("/http-in", request.getResponseBodyAsString());
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

@Override
protected void doDispatch(MuleEvent event) throws Exception {
    HttpMethod httpMethod = getMethod(event);
    httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint);

    try {/*from w  w w  . j a v a 2  s  .  c o  m*/
        execute(event, httpMethod);

        if (returnException(event, httpMethod)) {
            logger.error(httpMethod.getResponseBodyAsString());

            Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s",
                    httpMethod.getStatusCode(), httpMethod.getStatusText()));
            throw new DispatchException(event, getEndpoint(), cause);
        } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) {
            if (logger.isInfoEnabled()) {
                logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " "
                        + httpMethod.getStatusText());
            }
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.sso.CasGreeter.java

public String fetchServiceTicket(HttpMethod page) throws HttpException, IOException {
    client.executeMethod(page);/*from w w w.  j  ava2 s . c o m*/
    try {
        if (page.getStatusCode() != HttpStatus.SC_OK) {
            throw new Error("Cannot get login form");
        }
        return extractLoginTicket(page.getResponseBodyAsString());
    } finally {
        page.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.sso.CasGreeter.java

public String fetchServiceLocation(HttpMethod page) throws HttpException, IOException {
    client.executeMethod(page);/*ww  w  .j av a 2  s  .  c o m*/
    try {
        if (page.getStatusCode() != HttpStatus.SC_OK) {
            throw new Error("Cannot authenticate");
        }
        return extractRedirectLink(page.getResponseBodyAsString());
    } finally {
        page.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.platform.web.common.ajax.AjaxProxyServlet.java

protected static String doRequest(String method, String targetURL, HttpServletRequest req) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod;

    if ("GET".equals(method)) {
        httpMethod = new GetMethod(targetURL);
    } else if ("POST".equals(method)) {
        httpMethod = new PostMethod(targetURL);
        ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else if ("PUT".equals(method)) {
        httpMethod = new PutMethod(targetURL);
        ((PutMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else {/* w w w .j  a  v a  2  s.c  om*/
        throw new IllegalStateException("Unknown HTTP method: " + method);
    }

    Map<String, String[]> params = req.getParameterMap();
    for (String paramName : params.keySet()) {
        httpMethod.getParams().setParameter(paramName, params.get(paramName));
    }

    client.executeMethod(httpMethod);
    String body = httpMethod.getResponseBodyAsString();
    httpMethod.releaseConnection();
    return body;
}

From source file:org.nuxeo.ecm.tokenauth.TestAnonymousTokenAuthenticationServlet.java

@Test
public void testServletAsAnonymous() throws Exception {

    HttpClient httpClient = new HttpClient();

    HttpMethod getMethod = null;
    try {//w w  w. ja  va  2s  .  co m
        // ------------ Test anonymous user not allowed ----------------
        getMethod = new GetMethod(
                "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&deviceId=dead-beaf-cafe-babe&permission=rw");
        int status = httpClient.executeMethod(getMethod);
        assertEquals(401, status);

        // ------------ Test anonymous user allowed ----------------
        harness.deployContrib("org.nuxeo.ecm.platform.login.token.test",
                "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");

        status = httpClient.executeMethod(getMethod);
        assertEquals(201, status);
        String token = getMethod.getResponseBodyAsString();
        assertNotNull(token);
        assertNotNull(tokenAuthenticationService.getUserName(token));
        assertEquals(1, tokenAuthenticationService.getTokenBindings("Guest").size());

        harness.undeployContrib("org.nuxeo.ecm.platform.login.token.test",
                "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.tokenauth.TestTokenAuthenticationServlet.java

@Test
public void testServlet() throws Exception {

    HttpClient httpClient = new HttpClient();

    HttpMethod getMethod = null;
    try {//from www  . jav a2  s . c  o m
        // ------------ Test bad authentication ----------------
        getMethod = new GetMethod(
                "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&deviceId=dead-beaf-cafe-babe&permission=rw");
        int status = executeGetMethod(httpClient, getMethod, "Administrator", "badPassword");
        // Receives 404 because of redirection to error page
        assertEquals(404, status);

        // ------------ Test omitting required parameters ----------------
        // Token acquisition
        getMethod = new GetMethod("http://localhost:18080/authentication/token?applicationName=myFavoriteApp");
        status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator");
        assertEquals(400, status);

        // Token revocation
        getMethod = new GetMethod(
                "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&revoke=true");
        status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator");
        assertEquals(400, status);

        // ------------ Test acquiring token ----------------
        String queryParams = URIUtil
                .encodeQuery("applicationName=Nuxeo Drive&deviceId=dead-beaf-cafe-babe&permission=rw");
        URI uri = new URI("http", null, "localhost", 18080, "/authentication/token", queryParams, null);
        getMethod = new GetMethod(uri.toString());
        // Acquire new token
        status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator");
        assertEquals(201, status);
        String token = getMethod.getResponseBodyAsString();
        assertNotNull(token);
        assertNotNull(getTokenAuthenticationService().getUserName(token));
        assertEquals(1, getTokenAuthenticationService().getTokenBindings("Administrator").size());

        // Acquire existing token
        status = httpClient.executeMethod(getMethod);
        assertEquals(201, status);
        String existingToken = getMethod.getResponseBodyAsString();
        assertEquals(token, existingToken);

        // ------------ Test revoking token ----------------
        // Non existing token, should do nothing
        getMethod = new GetMethod(
                "http://localhost:18080/authentication/token?applicationName=nonExistingApp&deviceId=dead-beaf-cafe-babe&revoke=true");
        status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator");
        assertEquals(400, status);
        String response = getMethod.getResponseBodyAsString();
        assertEquals(String.format(
                "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                "Administrator", "nonExistingApp", "dead-beaf-cafe-babe"), response);

        // Existing token
        queryParams = URIUtil
                .encodeQuery("applicationName=Nuxeo Drive&deviceId=dead-beaf-cafe-babe&revoke=true");
        uri = new URI("http", null, "localhost", 18080, "/authentication/token", queryParams, null);
        getMethod = new GetMethod(uri.toString());
        status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator");
        assertEquals(202, status);
        response = getMethod.getResponseBodyAsString();
        assertEquals(String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                "Administrator", "Nuxeo Drive", "dead-beaf-cafe-babe"), response);
        nextTransaction(); // see committed changes
        assertNull(getTokenAuthenticationService().getUserName(token));
        assertTrue(getTokenAuthenticationService().getTokenBindings("Administrator").isEmpty());
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private synchronized Document doRequest(HttpMethod hm) {
    Document xml = null;/*from w  w  w  .ja v a2 s . c  o  m*/
    try {
        int ret = hc.executeMethod(hm);
        Header[] hs = hm.getResponseHeaders();
        for (Header h : hs) {
            System.err.println("head[" + h.getName() + "] => " + h.getValue());
        }
        if (ret == HttpStatus.SC_UNAUTHORIZED) {
            UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password);
            authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm);
            return null;
        } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) {
            InputStream is = hm.getResponseBodyAsStream();
            if (is != null) {
                if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) {
                    xml = DOMUtils.parse(is);
                    DOMUtils.logDom(xml);
                } else {
                    System.out.println(FileUtils.streamString(is, false));
                }
            }
        } else {
            System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        hm.releaseConnection();
    }
    return xml;
}

From source file:org.olat.modules.tu.TunnelComponent.java

private void fetchFirstResource(final Identity ident) {

    final TURequest tureq = new TURequest(); // config, ureq);
    tureq.setContentType(null); // not used
    tureq.setMethod("GET");
    tureq.setParameterMap(Collections.EMPTY_MAP);
    tureq.setQueryString(query);//from  w  ww  .  j  av a  2  s  .  co m
    if (startUri != null) {
        if (startUri.startsWith("/")) {
            tureq.setUri(startUri);
        } else {
            tureq.setUri("/" + startUri);
        }
    }

    // if (allowedToSendPersonalHeaders) {
    final String userName = ident.getName();
    final User u = ident.getUser();
    final String lastName = u.getProperty(UserConstants.LASTNAME, loc);
    final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc);
    final String email = u.getProperty(UserConstants.EMAIL, loc);

    tureq.setEmail(email);
    tureq.setFirstName(firstName);
    tureq.setLastName(lastName);
    tureq.setUserName(userName);
    // }

    final HttpMethod meth = fetch(tureq, httpClientInstance);
    if (meth == null) {
        setFetchError();
    } else {

        final Header responseHeader = meth.getResponseHeader("Content-Type");
        String mimeType;
        if (responseHeader == null) {
            setFetchError();
            mimeType = null;
        } else {
            mimeType = responseHeader.getValue();
        }

        if (mimeType != null && mimeType.startsWith("text/html")) {
            // we have html content, let doDispatch handle it for
            // inline rendering, update hreq for next content request
            String body;
            try {
                body = meth.getResponseBodyAsString();
            } catch (final IOException e) {
                Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class);
                htmlContent = "Error: cannot display inline :" + tureq.getUri()
                        + ": Unknown transfer problem '";
                return;
            }
            final SimpleHtmlParser parser = new SimpleHtmlParser(body);
            if (!parser.isValidHtml()) { // this is not valid HTML, deliver
                // asynchronuous
            }
            meth.releaseConnection();
            htmlHead = parser.getHtmlHead();
            jsOnLoad = parser.getJsOnLoad();
            htmlContent = parser.getHtmlContent();
        } else {
            htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType
                    + "' but expected 'text/html'. Response header was '" + responseHeader + "'.";
        }
    }
}

From source file:org.olat.modules.tu.TunnelComponent.java

/**
 * @see org.olat.core.gui.media.AsyncMediaResponsible#getAsyncMediaResource(org.olat.core.gui.UserRequest)
 *//* w ww .  java 2 s .c o  m*/
@Override
public MediaResource getAsyncMediaResource(final UserRequest ureq) {

    final String moduleURI = ureq.getModuleURI();
    // FIXME:fj: can we distinguish between a ../ call an a click to another component?
    // now works for start uri's like /demo/tunneldemo.php but when in tunneldemo.php
    // a link is used like ../ this link does not work (moduleURI is null). if i use
    // ../index.php instead everything works as expected
    if (moduleURI == null) { // after a click on some other component e.g.
        if (!firstCall) {
            return null;
        }
        firstCall = false; // reset first call
    }

    final TURequest tureq = new TURequest(config, ureq);

    // if (allowedToSendPersonalHeaders) {
    final String userName = ureq.getIdentity().getName();
    final User u = ureq.getIdentity().getUser();
    final String lastName = u.getProperty(UserConstants.LASTNAME, loc);
    final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc);
    final String email = u.getProperty(UserConstants.EMAIL, loc);
    tureq.setEmail(email);
    tureq.setFirstName(firstName);
    tureq.setLastName(lastName);
    tureq.setUserName(userName);
    // }

    final HttpMethod meth = fetch(tureq, httpClientInstance);
    if (meth == null) {
        setFetchError();
        return null;
    }

    final Header responseHeader = meth.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        setFetchError();
        return null;
    }

    final String mimeType = responseHeader.getValue();
    if (mimeType != null && mimeType.startsWith("text/html")) {
        // we have html content, let doDispatch handle it for
        // inline rendering, update hreq for next content request
        String body;
        try {
            body = meth.getResponseBodyAsString();
        } catch (final IOException e) {
            Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class);
            return null;
        }
        final SimpleHtmlParser parser = new SimpleHtmlParser(body);
        if (!parser.isValidHtml()) { // this is not valid HTML, deliver
            // asynchronuous
            return new HttpRequestMediaResource(meth);
        }
        meth.releaseConnection();
        htmlHead = parser.getHtmlHead();
        jsOnLoad = parser.getJsOnLoad();
        htmlContent = parser.getHtmlContent();
        setDirty(true);
    } else {
        return new HttpRequestMediaResource(meth); // this is a async browser
    }
    // refetch
    return null;
}