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.springbyexample.httpclient.HttpClientTemplate.java

/**
 * Processes <code>HttpMethod</code> by executing the method, 
 * validating the response, and calling the callback.
 * // ww w  .j av  a  2s. c  o  m
 * @param   httpMethod      <code>HttpMethod</code> to process.
 * @param   callback        Callback with HTTP method's response.
 */
protected void processHttpMethod(HttpMethod httpMethod, ResponseCallback<?> callback) {
    try {
        client.executeMethod(httpMethod);

        validateResponse(httpMethod);

        if (callback instanceof ResponseByteCallback) {
            ((ResponseByteCallback) callback).doWithResponse(httpMethod.getResponseBody());
        } else if (callback instanceof ResponseStreamCallback) {
            ((ResponseStreamCallback) callback).doWithResponse(httpMethod.getResponseBodyAsStream());
        } else if (callback instanceof ResponseStringCallback) {
            ((ResponseStringCallback) callback).doWithResponse(httpMethod.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        throw new HttpAccessException(e.getMessage(), e, httpMethod.getStatusCode());
    } catch (IOException e) {
        throw new HttpAccessException(e.getMessage(), e);
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Send the specified request payload to the specified HTTP endpoint using the method specified.
 * @param endpointURL The HTTP endpoint URL.
 * @param request The request payload.// w w  w.j  a v a  2  s.  co m
 * @param method The request method.
 * @return The HTTP response payload.
 */
public String sendString(String endpointURL, String request, String method) {
    String response = null;
    try {
        HttpMethod httpMethod = sendStringAndGetMethod(endpointURL, request, method);
        response = httpMethod.getResponseBodyAsString();
        httpMethod.releaseConnection();
    } catch (IOException ioe) {
        _logger.error("Unable to get response", ioe);
    }
    return response;
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * POST the specified classpath resource to the specified HTTP endpoint.
 * @param endpointURL The HTTP endpoint URL.
 * @param requestResource The classpath resource to be posted to the endpoint.
 * @return The HTTP response payload.//  ww w  . ja v a 2s.c om
 */
public String postResource(String endpointURL, String requestResource) {
    String response = null;
    try {
        HttpMethod httpMethod = postResourceAndGetMethod(endpointURL, requestResource);
        response = httpMethod.getResponseBodyAsString();
        httpMethod.releaseConnection();
    } catch (IOException ioe) {
        _logger.error("Unable to get response", ioe);
    }
    return response;
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Execute the supplied HTTP Method./*from  w  w  w  .ja  v  a 2  s  . c om*/
 * <p/>
 * Does not release the {@link org.apache.commons.httpclient.HttpMethod#releaseConnection() HttpMethod connection}.
 *
 * @param method The HTTP Method.
 * @return The HTTP Response.
 */
public String execute(HttpMethod method) {
    if (_httpClient == null) {
        Assert.fail(
                "HTTPMixIn not initialized.  You must call the initialize() method before using this MixIn");
    }

    for (String key : _requestHeaders.keySet()) {
        method.setRequestHeader(key, _requestHeaders.get(key));
    }

    if (_dumpMessages) {
        for (Header header : method.getRequestHeaders()) {
            _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]");
        }
    }

    String response = null;
    try {
        _httpClient.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (Exception e) {
        try {
            Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage());
        } catch (URIException e1) {
            _logger.error("Unexpected error", e1);
            return null;
        }
    }

    if (_dumpMessages) {
        for (Header header : method.getResponseHeaders()) {
            _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]");
        }
        _logger.info("Received response body:[" + response + "]");
    }

    for (String key : _expectedHeaders.keySet()) {
        Header actual = method.getResponseHeader(key);
        Assert.assertNotNull("Checking response header:[" + key + "]", actual);
        Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key),
                actual.getValue());
    }

    return response;
}

From source file:org.teiid.arquillian.IntegrationTestOData.java

@Test
public void testOdata() throws Exception {
    String vdb = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<vdb name=\"Loopy\" version=\"1\">\n"
            + "    <property name=\"UseConnectorMetadata\" value=\"true\" />\n"
            + "    <model name=\"MarketData\">\n"
            + "        <source name=\"text-connector2\" translator-name=\"loopback\" />\n"
            + "         <metadata type=\"DDL\"><![CDATA[\n"
            + "                CREATE FOREIGN TABLE G1 (e1 string, e2 integer PRIMARY KEY);\n"
            + "                CREATE FOREIGN TABLE G2 (e1 string, e2 integer PRIMARY KEY) OPTIONS (UPDATABLE 'true');\n"
            + "        ]]> </metadata>\n" + "    </model>\n" + "</vdb>";

    admin.deploy("loopy-vdb.xml", new ReaderInputStream(new StringReader(vdb), Charset.forName("UTF-8")));

    assertTrue(AdminUtil.waitForVDBLoad(admin, "Loopy", 1, 3));

    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "user"));

    HttpMethod method = new GetMethod("http://localhost:8080/odata/loopy.1/$metadata");
    int statusCode = client.executeMethod(method);
    assertTrue(statusCode == HttpStatus.SC_OK);
    assertEquals(//from  w  w  w  .j  a v a2s. c  o m
            ObjectConverterUtil.convertFileToString(UnitTestUtil.getTestDataFile("loopy-metadata-results.txt")),
            method.getResponseBodyAsString());
    method.releaseConnection();
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * {@inheritDoc}//  www .j a  v  a 2  s.c  o  m
 *
 * @see org.tuleap.mylyn.task.core.internal.client.rest.IRestConnector#sendRequest(org.apache.commons.httpclient.HttpMethod)
 */
@Override
public ServerResponse sendRequest(HttpMethod method) {
    // debug mode
    boolean debug = false;
    IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ITuleapConstants.TULEAP_PREFERENCE_NODE);
    if (node != null) {
        debug = node.getBoolean(ITuleapConstants.TULEAP_PREFERENCE_DEBUG_MODE, false);
    }

    if (hostConfiguration == null) {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, null);
    }

    method.setRequestHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Accept-Charset", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$

    WebUtil.configureHttpClient(httpClient, getUserAgent());

    Header[] responseHeaders = null;
    String responseBody = null;
    ServerResponse serverResponse = null;
    try {
        int code = WebUtil.execute(httpClient, hostConfiguration, method, null);
        responseBody = method.getResponseBodyAsString();
        responseHeaders = method.getResponseHeaders();
        if (debug) {
            debugRestCall(method, responseBody);
        }
        Map<String, String> rHeaders = new LinkedHashMap<String, String>();
        for (Header h : responseHeaders) {
            rHeaders.put(h.getName(), h.getValue());
        }
        serverResponse = new ServerResponse(code, responseBody, rHeaders);
    } catch (IOException e) {
        logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages
                .getString(TuleapCoreKeys.ioError, method.getName() + ' ' + method.getPath(), e.getMessage())));
        serverResponse = new ServerResponse(IO_ERROR_STATUS_CODE, "", Collections //$NON-NLS-1$
                .<String, String>emptyMap());
    } finally {
        method.releaseConnection();
    }

    return serverResponse;
}

From source file:org.wso2.appserver.integration.tests.javaee.jsf.JsfBValTestCase.java

@Test(groups = "wso2.as", description = "test JSF Bean Validation")
public void testJsfBVal() throws Exception {
    String CalculatorEndpoint = webAppURL + "/index.jsf";

    //here used Commons http client in order to manage same session throughout
    HttpMethod getMethod = new GetMethod(CalculatorEndpoint);
    HttpClient client = new HttpClient();

    client.executeMethod(getMethod);/*from ww  w . ja  va  2s .c  o  m*/
    String getResponse = getMethod.getResponseBodyAsString();
    log.info("getResponse - " + getResponse);

    //extracting jsf viewState from the get request
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource inputSource = new InputSource(new StringReader(getResponse));
    Document document = documentBuilder.parse(inputSource);

    //Evaluate XPath against Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//input[3]/@value", document.getDocumentElement(),
            XPathConstants.NODESET);
    String viewState = nodes.item(0).getNodeValue();

    HttpMethod postMethod = new PostMethod(CalculatorEndpoint);

    NameValuePair[] nameValuePairs = new NameValuePair[5];
    nameValuePairs[0] = new NameValuePair("j_id_4:j_id_8", "88");
    nameValuePairs[1] = new NameValuePair("j_id_4:j_id_b", "99");
    nameValuePairs[2] = new NameValuePair("j_id_4:j_id_c", "Calculate");
    nameValuePairs[3] = new NameValuePair("j_id_4_SUBMIT", "1");
    nameValuePairs[4] = new NameValuePair("javax.faces.ViewState", viewState);
    postMethod.setQueryString(nameValuePairs);

    client.executeMethod(postMethod);

    String postResponse = postMethod.getResponseBodyAsString();
    log.info("postResponse - " + postResponse);

    assertTrue(postResponse.contains("187"), "Response doesn't contain expected data");
}

From source file:org.wso2.appserver.integration.tests.javaee.jsf.JsfEjbTestCase.java

@Test(groups = "wso2.as", description = "test JSF Bean Validation")
public void testJsfEjb() throws Exception {
    String CalculatorEndpoint = webAppURL + "/index.jsf";

    //here used Commons http client in order to manage same session throughout
    HttpMethod getMethod = new GetMethod(CalculatorEndpoint);
    HttpClient client = new HttpClient();

    client.executeMethod(getMethod);/*from  w w  w .ja  v a 2s  . c  o m*/
    String getResponse = getMethod.getResponseBodyAsString();
    log.info("getResponse - " + getResponse);

    //extracting jsf viewState from the get request
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource inputSource = new InputSource(new StringReader(getResponse));
    Document document = documentBuilder.parse(inputSource);

    //Evaluate XPath against Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//input[4]/@value", document.getDocumentElement(),
            XPathConstants.NODESET);
    String viewState = nodes.item(0).getNodeValue();

    HttpMethod postMethod = new PostMethod(CalculatorEndpoint);

    NameValuePair[] nameValuePairs = new NameValuePair[4];
    nameValuePairs[0] = new NameValuePair("j_id_4:j_id_6", "John Doe");
    nameValuePairs[1] = new NameValuePair("j_id_4:j_id_7", "Enter");
    nameValuePairs[2] = new NameValuePair("j_id_4_SUBMIT", "1");
    nameValuePairs[3] = new NameValuePair("javax.faces.ViewState", viewState);
    postMethod.setQueryString(nameValuePairs);

    client.executeMethod(postMethod);

    String postResponse = postMethod.getResponseBodyAsString();
    log.info("postResponse - " + postResponse);

    assertTrue(postResponse.contains("Welcome John Doe"), "Response doesn't contain expected data");
    assertTrue(postResponse.contains("Distinct characters in the name: j, o, h, n, d, e"),
            "Response doesn't contain expected data");
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.HttpCommand.java

private SimpleHttpResponse toResponse(HttpMethod method) {
    SimpleHttpResponse response;/*from   w w w.  j  a  v  a  2  s.c  o  m*/
    Header[] headers = method.getResponseHeaders();
    String headersString = "";
    for (Header header : headers) {
        headersString += header.toString();
    }
    try {
        response = new SimpleHttpResponse(method.getStatusCode(), method.getStatusText(), headersString,
                method.getResponseBodyAsString());
    } catch (Exception e) {
        throw new RuntimeException("", e);
    }
    return response;
}

From source file:org.wso2.carbon.remotetasks.core.RemoteTask.java

@Override
public void execute() {
    boolean systemTask = this.isSystemTask();
    if (!systemTask) {
        this.notifyTaskManager();
    }/* ww w.ja  v  a  2  s. c  om*/
    String targetURI = this.getProperties().get(RemoteTasksConstants.REMOTE_TASK_URI);
    if (targetURI == null || targetURI.length() == 0) {
        return;
    }
    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(DEFAULT_CONNECTION_TIMEOUT);
    HttpMethod method = new GetMethod(targetURI);
    if (systemTask) {
        method.setRequestHeader(RemoteTasksConstants.REMOTE_SYSTEM_TASK_HEADER_ID,
                this.getProperties().get(RemoteTasksConstants.REMOTE_SYSTEM_TASK_ID));
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Executing remote task to URI: " + targetURI);
        }
        client.executeMethod(method);
        if (log.isDebugEnabled()) {
            StringBuilder builder = new StringBuilder();
            builder.append("Response Headers:-\n");
            for (Header header : method.getResponseHeaders()) {
                builder.append("\t" + header.getName() + ": " + header.getValue() + "\n");
            }
            log.debug(builder.toString());
        }
        String body = method.getResponseBodyAsString();
        if (log.isDebugEnabled()) {
            log.debug("Response Body:-\n\t" + body);
        }
        method.releaseConnection();
    } catch (Exception e) {
        log.error("Error executing remote task: " + e.getMessage(), e);
    }
}