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.apache.ode.axis2.httpbinding.HttpMethodConverter.java

public void parseHttpResponse(org.apache.ode.bpel.iapi.Message odeResponse, HttpMethod method, Operation opDef)
        throws SAXException, IOException {
    BindingOperation opBinding = binding.getBindingOperation(opDef.getName(), opDef.getInput().getName(),
            opDef.getOutput().getName());
    /* process headers */
    extractHttpResponseHeaders(odeResponse, method, opDef);

    /* process the body if any */

    // assumption is made that a response may have at most one body. HttpBindingValidator checks this.
    MIMEContent outputContent = WsdlUtils
            .getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
    int status = method.getStatusCode();

    boolean xmlExpected = outputContent != null && HttpUtils.isXml(outputContent.getType());
    // '202/Accepted' and '204/No Content' status codes explicitly state that there is no body, so we should not fail even if a part is bound to the body response
    boolean isBodyExpected = outputContent != null;
    boolean isBodyMandatory = isBodyExpected && bodyAllowed(status) && status != _202_ACCEPTED;
    final String body;
    try {//w ww . ja v  a2  s.  c o  m
        body = method.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException("Unable to get the request body : " + e.getMessage());
    }

    final boolean emptyBody = StringUtils.isEmpty(body);
    if (emptyBody) {
        if (isBodyMandatory) {
            throw new RuntimeException("Response body is mandatory but missing!");
        }
    } else {
        if (isBodyExpected) {
            Part partDef = opDef.getOutput().getMessage().getPart(outputContent.getPart());
            Element partElement;

            if (xmlExpected) {

                Header h = method.getResponseHeader("Content-Type");
                String receivedType = h != null ? h.getValue() : null;
                boolean contentTypeSet = receivedType != null;
                boolean xmlReceived = contentTypeSet && HttpUtils.isXml(receivedType);

                // a few checks
                if (!contentTypeSet) {
                    if (log.isDebugEnabled())
                        log.debug("Received Response with a body but no 'Content-Type' header!");
                } else if (!xmlReceived) {
                    if (log.isDebugEnabled())
                        log.debug("Xml type was expected but non-xml type received! Expected Content-Type="
                                + outputContent.getType() + " Received Content-Type=" + receivedType);
                }

                // parse the body and create the message part
                Element bodyElement = DOMUtils.stringToDOM(body);
                partElement = createPartElement(partDef, bodyElement);
            } else {
                // if not xml, process it as text
                partElement = createPartElement(partDef, body);
            }

            // set the part
            odeResponse.setPart(partDef.getName(), partElement);

        } else {
            // the body was not expected but we don't know how to deal with it
            if (log.isDebugEnabled())
                log.debug("Body received but not mapped to any part! Body=\n" + body);
        }
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

public Object[] parseFault(PartnerRoleMessageExchange odeMex, HttpMethod method) {
    Operation opDef = odeMex.getOperation();
    BindingOperation opBinding = binding.getBindingOperation(opDef.getName(), opDef.getInput().getName(),
            opDef.getOutput().getName());

    final String body;
    try {//from w  ww.j a  v a 2s  . com
        body = method.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException("Unable to get the request body : " + e.getMessage(), e);
    }
    Header h = method.getResponseHeader("Content-Type");
    String receivedType = h != null ? h.getValue() : null;
    if (opDef.getFaults().isEmpty()) {
        throw new RuntimeException("Operation [" + opDef.getName() + "] has no fault. This "
                + method.getStatusCode() + " error will be considered as a failure.");
    } else if (opBinding.getBindingFaults().isEmpty()) {
        throw new RuntimeException(
                "No fault binding. This " + method.getStatusCode() + " error will be considered as a failure.");
    } else if (StringUtils.isEmpty(body)) {
        throw new RuntimeException("No body in the response. This " + method.getStatusCode()
                + " error will be considered as a failure.");
    } else if (receivedType != null && !HttpUtils.isXml(receivedType)) {
        throw new RuntimeException("Response Content-Type [" + receivedType
                + "] does not describe XML entities. Faults must be XML. This " + method.getStatusCode()
                + " error will be considered as a failure.");
    } else {

        if (receivedType == null) {
            if (log.isWarnEnabled())
                log.warn("[Service: " + serviceName + ", Port: " + portName + ", Operation: " + opDef.getName()
                        + "] Received Response with a body but no 'Content-Type' header! Will try to parse nevertheless.");
        }

        // try to parse body
        final Element bodyElement;
        try {
            bodyElement = DOMUtils.stringToDOM(body);
        } catch (Exception e) {
            throw new RuntimeException("Unable to parse the response body as xml. This "
                    + method.getStatusCode() + " error will be considered as a failure.", e);
        }

        // Guess which fault it is
        QName bodyName = new QName(bodyElement.getNamespaceURI(), bodyElement.getNodeName());
        Fault faultDef = WsdlUtils.inferFault(opDef, bodyName);

        if (faultDef == null) {
            throw new RuntimeException("Unknown Fault Type [" + bodyName + "] This " + method.getStatusCode()
                    + " error will be considered as a failure.");
        } else if (!WsdlUtils.isOdeFault(opBinding.getBindingFault(faultDef.getName()))) {
            // is this fault bound with ODE extension?
            throw new RuntimeException("Fault [" + bodyName + "] is not bound with "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "fault") + ". This " + method.getStatusCode()
                    + " error will be considered as a failure.");
        } else {
            // a fault has only one part
            Part partDef = (Part) faultDef.getMessage().getParts().values().iterator().next();

            QName faultName = new QName(definition.getTargetNamespace(), faultDef.getName());
            QName faultType = faultDef.getMessage().getQName();

            // create the ODE Message now that we know the fault
            org.apache.ode.bpel.iapi.Message response = odeMex.createMessage(faultType);

            // build the element to be sent back
            Element partElement = createPartElement(partDef, bodyElement);
            response.setPart(partDef.getName(), partElement);

            // extract and set headers
            extractHttpResponseHeaders(response, method, opDef);
            return new Object[] { faultName, response };
        }
    }
}

From source file:org.apache.oodt.cas.filemgr.catalog.solr.SolrClient.java

/**
 * Common functionality for HTTP GET and POST requests.
 * @param method//from   w w  w.  java 2  s .  c  o  m
 * @return
 * @throws Exception
 */
private String doHttp(HttpMethod method) throws IOException, CatalogException {

    StringBuilder response = new StringBuilder();
    BufferedReader br = null;
    try {

        // send request
        HttpClient httpClient = new HttpClient();
        // OODT-719 Prevent httpclient from spawning closewait tcp connections
        method.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(method);

        // read response
        if (statusCode != HttpStatus.SC_OK) {

            // still consume the response
            method.getResponseBodyAsString();
            throw new CatalogException("HTTP method failed: " + method.getStatusLine());

        } else {

            // read the response body.
            br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                response.append(readLine);
            }

        }

    } finally {
        // must release the connection even if an exception occurred
        method.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception ignored) {
            }
        }
    }

    return response.toString();

}

From source file:org.apache.openejb.arquillian.session.SessionScopeTest.java

@Test
public void testShouldBeAbleToAccessServletAndEjb() throws Exception {
    String[] sessionResult = new String[2];
    for (int i = 0; i < sessionResult.length; i++) {
        HttpClient client = new HttpClient();
        HttpMethod get = new GetMethod(TEST_SESSION_URL);
        String[] contents = new String[2];
        try {//from ww  w.  j  a  v a2 s. c o m
            for (int j = 0; j < contents.length; j++) {
                int out = client.executeMethod(get);
                if (out != 200) {
                    throw new RuntimeException("get " + TEST_SESSION_URL + " returned " + out);
                }
                contents[j] = get.getResponseBodyAsString();
            }

            assertEquals(contents[0], contents[1]);
        } finally {
            get.releaseConnection();
        }
        sessionResult[i] = contents[0];
    }

    assertNotSame(sessionResult[0], sessionResult[1]);
}

From source file:org.apache.servicemix.http.ServerManagerTest.java

private String requestWithHttpClient(String url, String content) throws Exception {
    HttpMethod method;
    if (content != null) {
        PostMethod post = new PostMethod(url);
        post.setRequestEntity(new StringRequestEntity(content));
        method = post;//from w  w  w. j  a  va 2s.  c o  m
    } else {
        GetMethod get = new GetMethod(url);
        method = get;
    }
    new HttpClient().executeMethod(method);
    if (method.getStatusCode() != 200) {
        throw new InvalidStatusResponseException(method.getStatusCode());
    }
    return method.getResponseBodyAsString();
}

From source file:org.apache.shindig.social.sample.service.SampleContainerHandler.java

private String fetchStateDocument(String stateFileLocation) {
    String errorMessage = "The json state file " + stateFileLocation + " could not be fetched and parsed.";

    HttpMethod jsonState = new GetMethod(stateFileLocation);
    HttpClient client = new HttpClient();
    try {/*from ww w .j ava 2 s. c o  m*/
        client.executeMethod(jsonState);

        if (jsonState.getStatusCode() != 200) {
            throw new RuntimeException(errorMessage);
        }
        return jsonState.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException(errorMessage, e);
    } finally {
        jsonState.releaseConnection();
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyRequestValidator.java

/**
 * @param method the response method.//  w  w  w.  java2  s  .  c o  m
 * @return the body of the response from the server.
 * @throws IOException
 */
private String getResponseBody(HttpMethod method) throws IOException {
    final Header contentEncoding = method.getResponseHeader("Content-Encoding");
    if (contentEncoding != null && contentEncoding.getValue() != null
            && contentEncoding.getValue().contains("gzip")) {
        // then the server sent gzip - treat it so:
        final GZIPInputStream gzipIn = new GZIPInputStream(method.getResponseBodyAsStream());
        final String gunzippedEncodedJson = IOUtils.toString(gzipIn);
        gzipIn.close();
        return gunzippedEncodedJson;
    } else {
        // otherwise the server sent plaintext:
        if (method instanceof HttpMethodBase) {
            return ((HttpMethodBase) method).getResponseBodyAsString(16 * 1024 * 1024);
        }
        return method.getResponseBodyAsString();
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testValidatingCorrectFormCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "admin"));
    params.add(new NameValuePair("j_password", "admin"));
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_OK, params, null);
    assertTrue(post.getResponseBodyAsString().length() == 0);

    List<NameValuePair> params2 = new ArrayList<NameValuePair>();
    params2.add(new NameValuePair("j_validate", "true"));
    HttpMethod post2 = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_OK, params2, null);
    assertTrue(post2.getResponseBodyAsString().length() == 0);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testValidatingCorrectHttpBasicCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_OK, params, null);
    assertTrue(post.getResponseBodyAsString().length() == 0);

    HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true",
            HttpServletResponse.SC_OK);/*from   w ww.j av a  2  s  . c o m*/
    assertTrue(get.getResponseBodyAsString().length() == 0);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

private void assertXReason(final HttpMethod method) throws IOException {
    // expected the X-Reason header
    final Header reason = method.getResponseHeader("X-Reason");
    assertNotNull(reason);/*ww  w. j av  a 2s . c o m*/

    // expect the response to be the same as the reason (SLING-1831)
    assertEquals(reason.getValue(), method.getResponseBodyAsString().trim());
}