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.josso.test.tck.Tck004Test.java

protected void doPostCredentials1() throws Exception {
    NameValuePair username = new NameValuePair("josso_username", "user1");
    NameValuePair password = new NameValuePair("josso_password", "user1pwd");
    NameValuePair cmd = new NameValuePair(PARAM_JOSSO_CMD, "login");

    PostMethod postMethod = doPost("http://localhost:" + getProperty("josso.tck.serverPort")
            + "/josso/signon/usernamePasswordLogin.do", username, password, cmd);
    int status = postMethod.getStatusCode();
    assert status == HttpStatus.SC_MOVED_TEMPORARILY : "Unexpected HTTP status " + status;

    Header location = postMethod.getResponseHeader("Location");
    location.getValue();/*  ww  w .  jav  a 2 s . c  om*/
    HttpMethod getMethod = doGet(location.getValue());
    status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("role1") > 0 : "Role1 not found in response body";

}

From source file:org.josso.test.tck.Tck004Test.java

protected void doGetProtected2Delegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webapp2/protected-delegated-1.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("role1") > 0 : "Role1 not found in response body";

}

From source file:org.josso.test.tck.Tck004Test.java

protected void doGetProtectedADelegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webappA/protected-delegated-A.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("josso_username") > 0 : "No 'josso_username' field received in response";
    assert body.indexOf("josso_password") > 0 : "No 'josso_password' field received in response";

}

From source file:org.josso.test.tck.Tck004Test.java

protected void doPostCredentialsA() throws Exception {
    NameValuePair username = new NameValuePair("josso_username", "userA");
    NameValuePair password = new NameValuePair("josso_password", "user1pwd");
    NameValuePair cmd = new NameValuePair(PARAM_JOSSO_CMD, "login");

    PostMethod postMethod = doPost("http://localhost:" + getProperty("josso.tck.serverPort")
            + "/josso/signon/usernamePasswordLogin.do", username, password, cmd);
    int status = postMethod.getStatusCode();
    assert status == HttpStatus.SC_MOVED_TEMPORARILY : "Unexpected HTTP status " + status;

    Header location = postMethod.getResponseHeader("Location");
    location.getValue();/*  ww w.ja  v  a2  s.  c om*/
    HttpMethod getMethod = doGet(location.getValue());
    status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("roleA") > 0 : "Role1 not found in response body";

}

From source file:org.josso.test.tck.Tck004Test.java

protected void doGetProtectedBDelegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webappB/protected-delegated-A.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("roleA") > 0 : "Role1 not found in response body";

}

From source file:org.kalypso.util.net.URLGetter.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 */// w w  w.j  a v a  2s . co m
@Override
public IStatus execute(final IProgressMonitor monitor) {
    final String urlAsString = m_url.toString();
    final HttpMethod method = new GetMethod(urlAsString);
    // do not forget the next line!
    method.setDoAuthentication(true);

    final Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                final HttpClient httpClient = getHttpClient();
                httpClient.executeMethod(method);
                setResult(method.getResponseBodyAsStream());
            } catch (final IOException e) {
                final IStatus status;

                String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$
                try {
                    responseBodyAsString = method.getResponseBodyAsString();
                } catch (final IOException e1) {
                    final IStatus status2 = StatusUtilities.statusFromThrowable(e1);
                    KalypsoGisPlugin.getDefault().getLog().log(status2);
                }

                String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$
                if (responseBodyAsString != null && !responseBodyAsString.isEmpty())
                    message += "\n" + responseBodyAsString; //$NON-NLS-1$

                status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e);
                setStatus(status);
            }
        }
    };

    monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN);
    monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$
    thread.start();
    while (thread.isAlive()) {
        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
            // should never happen, ignore
            e1.printStackTrace();
        }

        final String statusText;
        final StatusLine statusLine = method.getStatusLine();
        if (statusLine == null)
            statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$
        else
            statusText = method.getStatusText();

        monitor.subTask(statusText);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            // TODO: this does not stop the thread!
            thread.interrupt();

            monitor.done();
            return Status.CANCEL_STATUS;
        }
    }

    monitor.done();
    return m_status;
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.impl.starinettester.dao.StarinetTesterDAO.java

/***********************************************************************************************
 * sendHttpRequest().//from   w  w w. ja v a2s .c  om
 * http://hc.apache.org/httpclient-3.x/tutorial.html
 * http://www.eboga.org/java/open-source/httpclient-demo.html
 *
 * @param commandmessage
 *
 * @return ResponseMessageInterface
 */

public ResponseMessageInterface sendHttpRequest(final CommandMessageInterface commandmessage) {
    final String SOURCE = "StarinetTesterDAO.sendHttpRequest()";
    final int PARAMETER_COUNT = 1;
    final int CHANNEL_COUNT = 1;
    final CommandType commandType;
    ResponseMessageInterface responseMessage;
    final HttpClient client;
    HttpMethod method;

    LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), SOURCE);

    // Get the latest Resources
    readResources();

    // Don't affect the CommandType of the incoming Command
    commandType = (CommandType) commandmessage.getCommandType().copy();
    responseMessage = null;

    // Do not change any DAO data containers!
    clearEventLogFragment();

    // Set up the HttpClient
    client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));

    // Initialise the Method with a default URL
    method = new GetMethod(DEFAULT_URL);

    try {
        final List<ParameterType> listParameters;

        // We expect one Parameter, the URL
        listParameters = commandType.getParameterList();

        if ((listParameters != null) && (listParameters.size() == PARAMETER_COUNT)
                && (SchemaDataType.STRING.equals(listParameters.get(0).getInputDataType().getDataTypeName()))) {
            final String strURLInput;
            final int intStatus;
            final String strResponseBody;

            strURLInput = listParameters.get(0).getValue();

            // Use the default URL if the Parameter was blank
            if ((strURLInput != null) && (!EMPTY_STRING.equals(strURLInput.trim()))) {
                method = new GetMethod(strURLInput);
            }

            // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
            // The User-Agent request-header field contains information about the user agent originating the request
            method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
            // The Referer[sic] request-header field allows the client to specify, for the server's benefit,
            // the address (URI) of the resource from which the Request-URI was obtained
            // (the "referrer", although the header field is misspelled.)
            method.setRequestHeader("Referer", strReferrerURL);

            SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.INFO,
                    METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_URL_REQUEST + strURLInput
                            + TERMINATOR + SPACE + METADATA_URL_REFERRER + strReferrerURL + TERMINATOR,
                    SOURCE, getObservatoryClock());
            // Now try to send the Request
            intStatus = client.executeMethod(method);

            // Check the server status
            if (intStatus != HttpStatus.SC_OK) {
                SimpleEventLogUIComponent
                        .logEvent(getEventLogFragment(), EventStatus.WARNING,
                                METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_MESSAGE
                                        + ERROR_HTTP + method.getStatusLine() + TERMINATOR,
                                SOURCE, getObservatoryClock());
            }

            // It is vital that the response body is *always* read,
            // regardless of the status returned by the server.
            strResponseBody = method.getResponseBodyAsString();

            if ((strResponseBody != null) && (getRawData() != null)) {
                final Vector vecResponseBody;

                // If we get here, it must have succeeded...
                // Add one channel of data, the Response
                // There must be one Calendar and ChannelCount samples in the Vector...
                vecResponseBody = new Vector(2);
                vecResponseBody.add(getObservatoryClock().getCalendarDateNow());
                vecResponseBody.add(strResponseBody);

                getRawData().add(vecResponseBody);
                setRawDataChannelCount(CHANNEL_COUNT);
                setTemperatureChannel(false);

                // Create the ResponseMessage
                // The ResponseValue is just 'Ok'
                commandType.getResponse().setValue(ResponseMessageStatus.SUCCESS.getResponseValue());

                responseMessage = ResponseMessageHelper.constructSuccessfulResponse(this, commandmessage,
                        commandType);
            } else {
                // No data are available
                SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING,
                        METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_MESSAGE
                                + ERROR_PARSE_DATA + TERMINATOR,
                        SOURCE, getObservatoryClock());
            }
        } else {
            throw new NumberFormatException(ResponseMessageStatus.INVALID_PARAMETER.getName());
        }
    }

    catch (NumberFormatException exception) {
        // Invalid Parameters
        SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL,
                METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_PARSE_INPUT
                        + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR,
                SOURCE, getObservatoryClock());
    }

    catch (IllegalArgumentException exception) {
        SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL,
                METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_PARSE_INPUT
                        + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR,
                SOURCE, getObservatoryClock());
    }

    catch (HttpException exception) {
        SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING,
                METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_HTTP
                        + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR,
                SOURCE, getObservatoryClock());
    }

    catch (IOException exception) {
        SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING,
                METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_IO
                        + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR,
                SOURCE, getObservatoryClock());
    }

    finally {
        method.releaseConnection();
    }

    // If the Command failed, do not change any DAO data containers!
    // Our valuable data must remain available for export later...
    responseMessage = ResponseMessageHelper.constructFailedResponseIfNull(this, commandmessage, commandType,
            responseMessage);
    return (responseMessage);
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;//from  w  ww . ja  v a2s. c  om
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.module.cxf.jaxws.CxfJaxWsTestCase.java

@Test
public void testHttpCall() throws Exception {
    HttpClient client = new HttpClient();
    // The format in which CXF processes the request in Http GET is:
    // http://host/service/OPERATION/PARAM_NAME/PARAM_VALUE
    // In this case: http://localhost:63081/Echo/echo/text/hello
    // (service: Echo corresponds to the name in the mule config file: TC-HTTP-CALL.xml)
    HttpMethod httpMethod = new GetMethod(
            "http://localhost:" + dynamicPort.getNumber() + "/services/Echo/echo/text/hello");
    // Http Status Code 200 means OK, the request has succeeded. (500 would indicate an error)
    assertEquals(200, client.executeMethod(httpMethod));
    // By default the class package - in its other way round - is used for the namespace:
    // Here, EchoServiceImpl classpath is: com\mulesoft\test\connectors\module\cxf
    // Therefore namespace should be: http://cxf.transport.connectors.test.mulesoft.com
    assertEquals(/*  w ww  . ja va 2 s.  c  o m*/
            "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>"
                    + "<ns2:echoResponse xmlns:ns2=\"http://testmodels.cxf.module.mule.org/\">"
                    + "<text>hello</text>" + "</ns2:echoResponse>" + "</soap:Body>" + "</soap:Envelope>",
            httpMethod.getResponseBodyAsString());
}

From source file:org.mule.transport.as2.As2MessageDispatcher.java

@Override
protected void doDispatch(MuleEvent event) throws Exception {
    logger.debug("DBG: inside " + getClass() + ".doDispatch()");
    HttpMethod httpMethod = getMethod(event);
    as2Connector.setupClientAuthorizationLocal(event, httpMethod, client, endpoint);

    try {//from  w w w  .  j  a  v  a2  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());
            }
        } else {
            logger.debug("DBG: response Body is: " + httpMethod.getResponseBodyAsString());
            /* Check the incoming synch MDN */
            MimeMultipart mdn = MDNBuilder.createMDNFromResponse(httpMethod.getResponseBodyAsStream(),
                    "multipart/report");
            if (MDNBuilder.identifyMdnType(mdn) != MdnType.PROCESSED) {
                throw new Exception("MDN is not of type PROCESSED");
            }
        }
    } finally {
        httpMethod.releaseConnection();
    }
}