Example usage for org.apache.commons.httpclient.util EncodingUtil getString

List of usage examples for org.apache.commons.httpclient.util EncodingUtil getString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util EncodingUtil getString.

Prototype

public static String getString(final byte[] data, String charset) 

Source Link

Document

Converts the byte array of HTTP content characters to a string.

Usage

From source file:com.cyberway.issue.net.LaxURI.java

protected static String decode(String component, String charset) throws URIException {
    if (component == null) {
        throw new IllegalArgumentException("Component array of chars may not be null");
    }/*from  w w  w . ja  v a2  s . c  o  m*/
    byte[] rawdata = null;
    //     try {
    rawdata = LaxURLCodec.decodeUrlLoose(EncodingUtil.getAsciiBytes(component));
    //     } catch (DecoderException e) {
    //         throw new URIException(e.getMessage());
    //     }
    return EncodingUtil.getString(rawdata, charset);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.methods.ExtendedDeleteMethod.java

public String getResponseBodyAsString() throws IOException {
    byte[] rawdata = getResponseBody();
    if (rawdata != null) {
        return EncodingUtil.getString(rawdata, getResponseCharSet());
    } else {/* w  w  w .  ja va  2  s .c  o m*/
        return null;
    }
}

From source file:edu.utah.further.core.ws.HttpResponseTo.java

/**
 * Returns the response body of the HTTP method, if any, as a {@link String}. If
 * response body is not available or cannot be read, returns <tt>null</tt> The string
 * conversion on the data is done using the character encoding specified in
 * <tt>Content-Type</tt> header. Buffers the response and this method can be called
 * several times yielding the same result each time.
 * //  ww w .  j a  va2s.  com
 * Note: This will cause the entire response body to be buffered in memory. A
 * malicious server may easily exhaust all the VM memory. It is strongly recommended,
 * to use getResponseAsStream if the content length of the response is unknown or
 * resonably large.
 * 
 * @return The response body or <code>null</code>.
 * 
 * @throws IOException
 *             If an I/O (transport) problem occurs while obtaining the response body.
 */
public String getResponseBodyAsString() throws IOException {
    final byte[] rawdata = isResponseAvailable() ? getResponseBody() : null;
    return (rawdata != null) ? EncodingUtil.getString(rawdata, getResponseCharSet()) : null;
}

From source file:org.alfresco.rest.api.tests.client.HttpResponse.java

public String getResponse() {
    if (responseBytes != null) {
        if (method instanceof HttpMethodBase) {
            // mimic method.getResponseBodyAsString
            return EncodingUtil.getString(responseBytes, ((HttpMethodBase) method).getResponseCharSet());
        } else {//from www  .ja v  a  2s  .  c om
            return new String(responseBytes);
        }
    } else {
        return null;
    }
}

From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java

protected String getResponseAsString(byte[] bytes, String responseCharSet) {
    if (bytes == null)
        return null;
    return EncodingUtil.getString(bytes, responseCharSet);
}

From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java

/**
 * Takes the HTTP Response Body from the HTTP Method and attempts to insert it into the response tree we are building.
 *
 * <p>Conversion Preference - 1) Try and parse as XML, if successful returns a Node 2) Try and parse as HTML returning as XML compatible HTML, if
 * successful returns a Node 3) Return as base64Binary encoded data</p>
 *
 * @param   context  The context of the calling XQuery
 * @param   method   The HTTP Request Method
 * @param   builder  The MemTreeBuilder that is being used
 *
 * @throws  IOException     //from   w w  w  .  j  a  v a2s.  c om
 * @throws  XPathException  
 */
private void insertResponseBody(final XQueryContext context, final HttpMethod method,
        final MemTreeBuilder builder, final Map<String, Boolean> parserFeatures,
        final Map<String, String> parserProperties) throws IOException, XPathException {
    NodeImpl responseNode = null;

    final InputStream bodyAsStream = method.getResponseBodyAsStream();

    // check if there is a response body
    if (bodyAsStream != null) {

        CachingFilterInputStream cfis = null;
        FilterInputStreamCache cache = null;
        try {

            //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
            cache = FilterInputStreamCacheFactory
                    .getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration() {
                        @Override
                        public String getCacheClass() {
                            return (String) context.getBroker().getConfiguration()
                                    .getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                        }
                    });

            cfis = new CachingFilterInputStream(cache, bodyAsStream);

            //mark the start of the stream
            cfis.mark(Integer.MAX_VALUE);

            // determine the type of the response document
            final Header responseContentType = method.getResponseHeader("Content-Type");

            final MimeType responseMimeType = getResponseMimeType(responseContentType);
            if (responseContentType != null) {
                builder.addAttribute(new QName("mimetype", null, null), responseContentType.getValue());
            }

            //try and parse the response as XML
            try {
                //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);
                responseNode = (NodeImpl) ModuleUtils.streamToXML(context, shieldedInputStream);
                builder.addAttribute(new QName("type", null, null), "xml");
                responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
            } catch (final SAXException se) {
                // could not parse to xml
                // not an error in itself, it will be treated either as HTML,
                // text or binary here below
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not parse http response content as XML (will try html, text or fallback to binary): "
                        + se.getMessage();
                if (logger.isDebugEnabled()) {
                    logger.debug(msg, se);
                } else {
                    logger.info(msg);
                }
            } catch (final IOException ioe) {
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not read http response content: " + ioe.getMessage();
                logger.error(msg, ioe);
                throw new XPathException(msg, ioe);
            }

            if (responseNode == null) {
                //response is NOT parseable as XML

                //is it a html document?
                if (responseMimeType.getName().equals(MimeType.HTML_TYPE.getName())) {

                    //html document
                    try {

                        //reset the stream to the start, as we need to reuse since attempting to parse to XML
                        cfis.reset();

                        //parse html to xml(html)

                        //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                        final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);

                        responseNode = (NodeImpl) ModuleUtils
                                .htmlToXHtml(context, method.getURI().toString(),
                                        new InputSource(shieldedInputStream), parserFeatures, parserProperties)
                                .getDocumentElement();
                        builder.addAttribute(new QName("type", null, null), "xhtml");
                        responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
                    } catch (final URIException ue) {
                        throw new XPathException(this, ue.getMessage(), ue);
                    } catch (final SAXException se) {
                        //could not parse to xml(html)
                        logger.debug(
                                "Could not parse http response content from HTML to XML: " + se.getMessage(),
                                se);
                    }
                }
            }

            if (responseNode == null) {

                //reset the stream to the start, as we need to reuse since attempting to parse to HTML->XML
                cfis.reset();

                if (responseMimeType.getName().startsWith("text/")) {

                    // Assume it's a text body and URL encode it
                    builder.addAttribute(new QName("type", null, null), "text");
                    builder.addAttribute(new QName("encoding", null, null), "URLEncoded");

                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    final byte buf[] = new byte[4096];
                    int read = -1;
                    while ((read = cfis.read(buf)) > -1) {
                        baos.write(buf);
                    }

                    builder.characters(URLEncoder.encode(EncodingUtil.getString(baos.toByteArray(),
                            ((HttpMethodBase) method).getResponseCharSet()), "UTF-8"));
                    baos.close();
                } else {

                    // Assume it's a binary body and Base64 encode it
                    builder.addAttribute(new QName("type", null, null), "binary");
                    builder.addAttribute(new QName("encoding", null, null), "Base64Encoded");

                    BinaryValue binary = null;
                    try {
                        binary = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                                cfis);
                        builder.characters(binary.getStringValue());
                    } finally {
                        // free resources
                        if (binary != null) {
                            binary.destroy(context, null);
                        }
                    }
                }
            }
        } finally {
            if (cache != null) {
                try {
                    cache.invalidate();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }

            if (cfis != null) {
                try {
                    cfis.close();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
        }
    }
}