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.bgp4j.management.web.WebManagementServerTest.java

@Test
public void testInjectedTestBean() throws Exception {
    ManagementApplication.addRegisteredSingleton(testResource);

    server.setConfiguration(httpServerConfiguration);
    server.startServer();//from ww w  .jav a  2 s . c o  m

    Thread.sleep(1000);

    InetSocketAddress serverAddress = httpServerConfiguration.getServerConfiguration().getListenAddress();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("http://" + serverAddress.getAddress().getHostAddress() + ":"
            + serverAddress.getPort() + "/rest/test/bean");

    Assert.assertEquals(HttpServletResponse.SC_OK, client.executeMethod(method));
    Assert.assertEquals("found", method.getResponseBodyAsString());

    server.stopServer();
}

From source file:org.bonitasoft.connectors.webdav.exo.common.ExoConnector.java

/**
 * process response to get statusCode, statusText and response string.
 * //from  ww  w.  j  av  a  2 s  .c  o m
 * @param httpMethod
 * @param getResponseAsString
 */
protected void processResponse(final HttpMethod httpMethod, final boolean getResponseAsString) {

    String statusCode = "-1";
    if (httpMethod.getStatusCode() > 0) {
        statusCode = String.valueOf(httpMethod.getStatusCode());
    }
    final String statusText = httpMethod.getStatusText();

    String responseString = "";
    if (getResponseAsString) {
        try {
            responseString = httpMethod.getResponseBodyAsString();
            if (responseString == null) {
                responseString = "";
            }
        } catch (final IOException e) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning("IOException while getting responseAsString: " + e.getMessage());
            }
            e.printStackTrace();
        }
    }

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("status CODE: " + statusCode + ", status TEXT: " + statusText + "\n response string: "
                + responseString);
    }
    this.statusCode = statusCode;
    this.statusText = statusText;
    this.response = responseString;
}

From source file:org.cauldron.tasks.HttpCall.java

/**
 * Running an HttpTask retrieves the path contents according to the task
 * attributes. POST body comes from the input.
 *//*from   w  w w.ja  va2s  .  c  om*/

public Object run(Context context, Object input) throws TaskException {
    // For POST, body must be available as input.

    String body = null;
    if (!isGet) {
        body = (String) context.convert(input, String.class);
        if (body == null)
            throw new TaskException("HTTP POST input must be convertible to String");
    }

    // Prepare request parameters.

    NameValuePair[] nvp = null;
    if (params != null && params.size() > 0) {
        nvp = new NameValuePair[params.size()];
        int count = 0;

        for (Iterator entries = params.entrySet().iterator(); entries.hasNext();) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            nvp[count++] = new NameValuePair(key, value);
        }
    }

    // Create the retrieval method and set parameters.
    //

    HttpMethod method;
    if (isGet) {
        GetMethod get = new GetMethod();
        if (nvp != null)
            get.setQueryString(nvp);
        method = get;
    } else {
        PostMethod post = new PostMethod();
        post.setRequestBody(body);
        if (nvp != null)
            post.addParameters(nvp);
        method = post;
    }

    // Make the call.

    method.setPath(path);
    HttpConnection connection = connectionManager.getConnection(config);

    try {
        connection.open();
        method.execute(new HttpState(), connection);
        return method.getResponseBodyAsString();
    } catch (HttpException e) {
        throw new TaskException(e);
    } catch (IOException e) {
        throw new TaskException(e);
    } finally {
        connection.close();
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedText.java

public void setResponse(HttpMethod method, int status) throws Exception {
    text = method.getResponseBodyAsString();
    this.status = status;
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL.java

public void setResponse(HttpMethod method, int status) throws Exception {
    String possiblemessg = method.getResponseBodyAsString();
    Header location = method.getResponseHeader("Location");
    if (location == null) {
        if (possiblemessg != "") {
            throw new ConnectionException(possiblemessg, status, "");
        }//w ww.  j  a va 2 s .  co m
        throw new ConnectionException("Missing location header " + method.getResponseBodyAsString(), status,
                "");
    }
    url = location.getValue();
    this.status = status;
}

From source file:org.craftercms.cstudio.publishing.processor.CacheInvalidatePostProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    HttpMethod cacheInvalidateGetMethod = new GetMethod(cacheInvalidateUrl);
    HttpClient client = new HttpClient();
    try {/*from  w  ww.  j a  va  2 s  .  c  om*/
        int status = client.executeMethod(cacheInvalidateGetMethod);
        if (status != HttpServletResponse.SC_OK) {
            throw new PublishingException("Unable to invalidate cache: URL " + cacheInvalidateUrl
                    + " returned status '" + cacheInvalidateGetMethod.getStatusText() + "' with body \n"
                    + cacheInvalidateGetMethod.getResponseBodyAsString());
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Cache invalidated: URL " + cacheInvalidateUrl + " returned status '"
                        + cacheInvalidateGetMethod.getStatusText() + "'");
            }
        }
    } catch (IOException e) {
        throw new PublishingException(e);
    } finally {
        cacheInvalidateGetMethod.releaseConnection();
    }
}

From source file:org.deegree.portal.cataloguemanager.control.DeleteMetadataListener.java

@SuppressWarnings("unchecked")
public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException {

    try {//w ww.  j a  v  a2 s .c o  m
        CatalogueManagerConfiguration conf = getCatalogueManagerConfiguration(event);
        String id = (String) event.getParameter().get("ID");

        URL url = getClass().getResource("/org/deegree/portal/cataloguemanager/control/resources/delete.xml");
        String s = FileUtils.readTextFile(url).toString();
        s = StringTools.replace(s, "$id$", id, false);
        XMLFragment xml = new XMLFragment();
        xml.load(new StringReader(s), XMLFragment.DEFAULT_URL);

        Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
        Map<String, String> map = new HashMap<String, String>();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                    && !name.equalsIgnoreCase("user-agent")) {
                map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
            }
        }
        HttpMethod post = HttpUtils.performHttpPost(conf.getCatalogueURL(), xml, 60000, null, null, map);
        s = post.getResponseBodyAsString();
        if (s.toLowerCase().indexOf("exception") > -1) {
            ExceptionBean eb = new ExceptionBean(getClass().getName(), "delete failed");
            responseHandler.writeAndClose(true, eb);
        } else {
            responseHandler.writeAndClose("insert performed");
        }
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, eb);
        return;
    }

}

From source file:org.deegree.portal.cataloguemanager.control.InsertMetadataListener.java

@SuppressWarnings("unchecked")
private String insertIntoCSW(ResponseHandler responseHandler, MDMetadata mdMetadata)
        throws JAXBException, IOException, HttpException, SAXException, XMLParsingException {

    JAXBContext jc = JAXBContext.newInstance("org.deegree.portal.cataloguemanager.model");
    Marshaller m = jc.createMarshaller();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
    m.marshal(mdMetadata, bos);//from  w  w w .jav a  2 s  . c o  m
    XMLFragment md = new XMLFragment();
    md.load(new ByteArrayInputStream(bos.toByteArray()), XMLFragment.DEFAULT_URL);
    // FileUtils.writeToFile( "e:/temp/servicemetadata.xml", md.getAsPrettyString() );
    URL url = getClass().getResource("/org/deegree/portal/cataloguemanager/control/resources/insert.xml");
    XMLFragment insert = new XMLFragment(url);
    Element elem = XMLTools.getElement(insert.getRootElement(), "csw202:Insert",
            CommonNamespaces.getNamespaceContext());
    XMLTools.copyNode(md.getRootElement().getOwnerDocument(), elem);

    Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
    Map<String, String> map = new HashMap<String, String>();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                && !name.equalsIgnoreCase("user-agent")) {
            map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
        }
    }
    HttpMethod post = HttpUtils.performHttpPost(conf.getCatalogueURL(), insert, 60000, null, null, map);
    String s = post.getResponseBodyAsString();
    if (s.toLowerCase().indexOf("exception") > -1) {
        ExceptionBean eb = new ExceptionBean(getClass().getName(), "insert failed");
        responseHandler.writeAndClose(true, eb);
    } else {
        responseHandler.writeAndClose("insert performed");
    }

    return s;
}

From source file:org.deegree.portal.cataloguemanager.control.UpdateMetadataListener.java

@SuppressWarnings("unchecked")
private String updateCSW(ResponseHandler responseHandler, MDMetadata mdMetadata)
        throws JAXBException, IOException, HttpException, SAXException {

    JAXBContext jc = JAXBContext.newInstance("org.deegree.portal.cataloguemanager.model");
    Marshaller m = jc.createMarshaller();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
    m.marshal(mdMetadata, bos);//from  ww  w.  j a  v a2  s.co  m

    URL url = getClass().getResource("/org/deegree/portal/cataloguemanager/control/resources/update.xml");
    String s = FileUtils.readTextFile(url).toString();
    String t = new String(bos.toByteArray());
    int c = t.indexOf("?>");
    t = t.substring(c + 2);
    s = StringTools.replace(s, "$id$", mdMetadata.getFileIdentifier().getCharacterString(), false);
    s = StringTools.replace(s, "$data$", t, false);
    String csw = conf.getCatalogueURL();

    XMLFragment xml = new XMLFragment(new StringReader(s), XMLFragment.DEFAULT_URL);
    Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
    Map<String, String> map = new HashMap<String, String>();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                && !name.equalsIgnoreCase("user-agent")) {
            map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
        }
    }
    HttpMethod post = HttpUtils.performHttpPost(csw, xml, 60000, null, null, map);
    s = post.getResponseBodyAsString();
    if (s.toLowerCase().indexOf("exception") > -1) {
        ExceptionBean eb = new ExceptionBean(getClass().getName(), "update failed");
        responseHandler.writeAndClose(true, eb);
    } else {
        responseHandler.writeAndClose("insert performed");
    }

    return s;
}

From source file:org.dspace.ctask.demo.GoogleTranslator.java

@Override
protected String translateText(String from, String to, String text) throws IOException {

    log.debug("Performing API call to translate from " + from + " to " + to);

    text = URLEncoder.encode(text, "UTF-8");

    String translatedText = null;

    String url = baseUrl + "?key=" + apiKey;
    url += "&source=" + from + "&target=" + to + "&q=" + text;

    HttpClient client = new HttpClient();
    HttpMethod hm = new GetMethod(url);
    int code = client.executeMethod(hm);
    log.debug("Response code from API call is " + code);

    if (code == 200) {
        String response = hm.getResponseBodyAsString();
        try {/*from   w  ww  .  ja  v  a2  s .  c o m*/
            JSONArray ja = JSONArray.fromObject(
                    JSONObject.fromObject(JSONObject.fromObject(response).get("data")).get("translations"));

            if (ja.size() > 0) {
                JSONObject jt = ja.getJSONObject(0);
                translatedText = jt.get("translatedText").toString();
                translatedText = StringEscapeUtils.unescapeHtml(translatedText);
            }

        } catch (Exception e) {
            log.info("Error reading Google API response: " + e.getLocalizedMessage());
        }

    }

    return translatedText;
}