package com.jware.util.xml;

import java.io.IOException;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.EncodingUtil;

public class PostMethodUtil extends PostMethod {

    /**
     * 
     */
    public PostMethodUtil() {
        super();
    }

    /**
     * @param uri
     */
    public PostMethodUtil(String uri) {
        super(uri);
    }

    /**
     * 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.
     * 
     * 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.
     * 
     * @throws IOException If an I/O (transport) problem occurs while obtaining the 
     * response body.
     */
    public String getResponseBodyAsString(String charset) throws IOException {
        byte[] rawdata = null;
        if (super.getResponseStream()!=null || super.getResponseBody()!=null ) {
            rawdata = getResponseBody();
        }
        if (rawdata != null) {
            return EncodingUtil.getString(rawdata, (charset!=null?charset:getResponseCharSet()));
        } else {
            return null;
        }
    }

    /**
     * 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.
     * 
     * 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.
     * 
     * @throws IOException If an I/O (transport) problem occurs while obtaining the 
     * response body.
     */
    public byte[] getResponseBodyAsByte() throws IOException {
        byte[] rawdata = null;
        if (super.getResponseStream()!=null || super.getResponseBody()!=null ) {
            rawdata = getResponseBody();
        }
        return rawdata;
    }

}
