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.intermine.webservice.server.VersionServiceTest.java

@Test
public void wsVersionJSON() throws Exception {
    HttpMethod get = new GetMethod(baseurl + "/version/json");
    try {/*w ww.  j a v a  2 s . c  o m*/
        int statusCode = client.executeMethod(get);
        assertEquals("Request should be successful", 200, statusCode);
        JSONObject resp = new JSONObject(get.getResponseBodyAsString());
        assertEquals("Version should be " + expectedVersion, expectedVersion, resp.getInt("version"));
    } finally {
        get.releaseConnection();
    }
}

From source file:org.intermine.webservice.server.VersionServiceTest.java

@Test
public void wsVersionJSONP() throws Exception {
    HttpMethod get = new GetMethod(baseurl + "/version?callback=foo");
    try {//from ww w . j  av  a2  s .  co  m
        int statusCode = client.executeMethod(get);
        assertEquals("Request should be successful", 200, statusCode);
        String body = get.getResponseBodyAsString();
        assertTrue("JSONP responses have the callback", body.startsWith("foo"));
        String json = body.substring(body.indexOf("foo(") + 4, body.length() - 1);
        JSONObject resp = new JSONObject(json);
        assertEquals("Version should be " + expectedVersion, expectedVersion, resp.getInt("version"));
    } finally {
        get.releaseConnection();
    }
}

From source file:org.j2free.http.HttpCallResult.java

/**
 * // ww  w  . j  a  v a2  s  .c  o  m
 * @param method
 * @throws IOException
 */
public HttpCallResult(HttpMethod method) throws IOException {

    this.method = method;
    this.response = method.getResponseBodyAsString();
    this.bytes = method.getResponseBody();

    requestHeaders = new HashMap();
    responseHeaders = new HashMap();

    Header[] headers = method.getRequestHeaders();
    for (Header header : headers) {
        requestHeaders.put(header.getName(), header);
    }

    headers = method.getResponseHeaders();
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header);
    }

    status = method.getStatusLine();
}

From source file:org.jasig.portal.security.provider.SamlAssertionFilter.java

public void doHttpFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("HTTP headers: [" + headersAsString(req) + "]");
    }/*from   w w w.j a  v a  2 s.  c om*/

    final int assertionCount = this.getAssertionCount(req);

    String idp = null, assertion = null, signingKeys = null;

    if (assertionCount > 0) {
        idp = req.getHeader("Shib-Identity-Provider");
        final String firstAssertionHeader = req.getHeader("Shib-Assertion-01");

        if (idpPublicKeysSessionAttributeName != null) {
            signingKeys = req.getHeader("Meta-Signing-Keys");
        }

        if (StringUtils.isNotEmpty(firstAssertionHeader)) {
            if (logger.isInfoEnabled()) {
                logger.info("Retrieving SAML assertion from the URL: " + firstAssertionHeader);
            }
            final HttpMethod method = new GetMethod(firstAssertionHeader);

            try {
                int result = this.httpClient.executeMethod(method);

                if (result >= HttpStatus.SC_OK && result < 300) {
                    assertion = method.getResponseBodyAsString();
                } else {
                    logger.error("Unsupported HTTP result code when retrieving the SAML assertion: " + result);
                }
            } catch (Exception ex) {
                // There is nothing that can be done about this exception other than to log it
                // Exception must be caught and not rethrown to allow normal processing to continue
                logger.error("Exception caught when trying to retrieve SAML assertion.", ex);
            } finally {
                method.releaseConnection();
            }
        } else {
            logger.error("SAML assertion URL not present, but the assertion count was " + assertionCount + ".");
        }
    } else {
        logger.warn("SAML assertion count not present or zero");
    }

    // Start with processing the login.  This way if the login process creates a new session,
    // the assertion will remain in the session to be picked up by SamlAssertionUserInfoService
    try {
        chain.doFilter(req, res);
    } finally {
        HttpSession session = req.getSession();

        if (assertion != null) {
            session.setAttribute(samlAssertionSessionAttributeName, assertion);
        }
        if (idp != null) {
            session.setAttribute("IdP", idp);
        }
        if (signingKeys != null) {
            session.setAttribute(idpPublicKeysSessionAttributeName, signingKeys);
        }
    }
}

From source file:org.jboss.seam.conversation.test.SmokeBase.java

@Test
public void testFactory() throws Exception {
    Thread.sleep(1000L);/* ww w .j  a  v a  2 s .  co m*/

    SimpleHttpConnectionManager connManager = new SimpleHttpConnectionManager(true);
    HttpClient client = new HttpClient(connManager);

    HttpMethod method = new GetMethod(Deployments.CONTEXT_PATH + "dummy/");
    int response = client.executeMethod(method);
    Assert.assertEquals(200, response);
    Assert.assertEquals("OK", method.getResponseBodyAsString());

    method = new GetMethod(Deployments.CONTEXT_PATH + "dummy/?cid=1234");
    response = client.executeMethod(method);
    Assert.assertEquals(200, response);
    Assert.assertEquals("OK", method.getResponseBodyAsString());
}

From source file:org.jboss.test.faces.jetty.JettyServerTestCase.java

@Test
public void testHelloPage() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(
            new URL("http", "localhost", PORT, "/hello-jetty.jsf?name=JettyServer").toExternalForm());

    try {//  ww  w  .j  a  v a 2 s . c om
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            fail("Method failed: " + method.getStatusLine());
        }

        String responseBodyAsString = method.getResponseBodyAsString();
        assertTrue(responseBodyAsString.contains("Hello, JettyServer!"));

    } finally {
        method.releaseConnection();
    }
}

From source file:org.jboss.test.web.jbas8318.unit.ResourceInjectionOnNonJavaEEComponentsTestCase.java

/**
 * Test that Java EE resource injection in a servlet works as expected
 *
 * @throws Exception/*from w w  w . j  a v  a 2  s.com*/
 */
public void testInjectionInServlet() throws Exception {
    URL url = new URL(baseURL + "jbas-8318/SimpleServlet");
    HttpMethod request = HttpUtils.accessURL(url);
    String response = request.getResponseBodyAsString();
    logger.info("Response for url " + url + " is " + response);
    assertEquals("Unexpected response from servlet", SimpleServlet.SUCCESS_MESSAGE, response);
}

From source file:org.jboss.test.web.jbas8318.unit.ResourceInjectionOnNonJavaEEComponentsTestCase.java

/**
 * Tests that Java EE resource injection in a JSF managed bean works as expected
 *
 * @throws Exception//from   w w  w .  j  a  va  2  s .c  om
 */
public void testInjectionInJSFManagedBean() throws Exception {
    URL url = new URL(baseURL + "jbas-8318/test-jsf-injection.jsf");
    HttpMethod request = HttpUtils.accessURL(url);
    int statusCode = request.getStatusCode();
    logger.info("Got status code: " + statusCode + " for URL " + url);
    String response = request.getResponseBodyAsString();
    logger.info("Response for URL " + url + " is " + response);
    // no exceptions == injection worked fine and test passed.
    // TODO: We might want to test for the html output to really make sure of the output.
}

From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    // extract required parameters
    String urlStr = (String) workItem.getParameter("Url");
    String method = (String) workItem.getParameter("Method");
    if (urlStr == null) {
        throw new IllegalArgumentException("Url is a required parameter");
    }//from   w ww .j a  v a2s  .  c  o  m
    if (method == null || method.trim().length() == 0) {
        method = "GET";
    }
    Map<String, Object> params = workItem.getParameters();

    // optional timeout config parameters, defaulted to 60 seconds
    Integer connectTimeout = (Integer) params.get("ConnectTimeout");
    if (connectTimeout == null)
        connectTimeout = 60000;
    Integer readTimeout = (Integer) params.get("ReadTimeout");
    if (readTimeout == null)
        readTimeout = 60000;

    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout);
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);

    HttpMethod theMethod = null;
    if ("GET".equals(method)) {
        theMethod = new GetMethod(urlStr);
    } else if ("POST".equals(method)) {
        theMethod = new PostMethod(urlStr);
        setBody(theMethod, params);
    } else if ("PUT".equals(method)) {
        theMethod = new PutMethod(urlStr);
        setBody(theMethod, params);
    } else if ("DELETE".equals(method)) {
        theMethod = new DeleteMethod(urlStr);
    } else {
        throw new IllegalArgumentException("Method " + method + " is not supported");
    }
    doAuthorization(httpclient, theMethod, params);
    try {
        int responseCode = httpclient.executeMethod(theMethod);
        Map<String, Object> results = new HashMap<String, Object>();
        if (responseCode >= 200 && responseCode < 300) {
            theMethod.getResponseBody();
            postProcessResult(theMethod.getResponseBodyAsString(), results);
            results.put("StatusMsg",
                    "request to endpoint " + urlStr + " successfully completed " + theMethod.getStatusText());
        } else {
            logger.warn("Unsuccessful response from REST server (status {}, endpoint {}, response {}",
                    responseCode, urlStr, theMethod.getResponseBodyAsString());
            results.put("StatusMsg",
                    "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString());
        }
        results.put("Status", responseCode);

        // notify manager that work item has been completed
        manager.completeWorkItem(workItem.getId(), results);
    } catch (Exception e) {
        handleException(e);
    } finally {
        theMethod.releaseConnection();
    }
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

public static void httpGet(final URI serverUri, final String downloadUrl, final OutputStream outputStream,
        Credentials credentials, final HttpClient httpClient) throws TfsException, IOException {
    TFSVcs.assertTrue(downloadUrl != null);
    setupHttpClient(credentials, serverUri, httpClient);

    HttpMethod method = new GetMethod(downloadUrl);
    try {//from  ww w  .  j  a va  2 s  .c  om
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            StreamUtil.copyStreamContent(getInputStream(method), outputStream);
        } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new OperationFailedException(method.getResponseBodyAsString());
        } else {
            throw TfsExceptionManager.createHttpTransportErrorException(statusCode, null);
        }
    } finally {
        // enforce connection release since GZipInputStream may not trigger underlying AutoCloseInputStream.close()
        method.releaseConnection();
    }
}