Example usage for org.apache.commons.httpclient HttpMethod getURI

List of usage examples for org.apache.commons.httpclient HttpMethod getURI

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getURI.

Prototype

public abstract URI getURI() throws URIException;

Source Link

Usage

From source file:org.apache.camel.component.http.HttpProducer.java

public void process(Exchange exchange) throws Exception {
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;

    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString);
        }/*from   w  w  w .j  a v  a2  s  . com*/
        // Need to remove the Host key as it should be not used 
        exchange.getIn().getHeaders().remove("host");
    }
    HttpMethod method = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        HttpMethodParams params = method.getParams();
        params.setVersion(HttpVersion.parse(httpProtocolVersion));
    }

    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);

        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);

            // the value to add as request header
            final List<String> values = new ArrayList<String>();

            // if its a multi value then check each value if we can add it and for multi values they
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());

                // we should not add headers for the parameters in the uri if we bridge the endpoint
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null
                        && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }

            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                method.addRequestHeader(key, s);
            }
        }
    }

    // lets store the result in the output message.
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
        }
        int responseCode = executeMethod(method);
        LOG.debug("Http responseCode: {}", responseCode);

        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, method, in, strategy, responseCode);
        } else {
            if (responseCode >= 100 && responseCode < 300) {
                // only populate response for OK response
                populateResponse(exchange, method, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, method, responseCode);
            }
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.camel.component.http.HttpProducer.java

protected Exception populateHttpOperationFailedException(Exchange exchange, HttpMethod method, int responseCode)
        throws IOException, ClassNotFoundException {
    Exception answer;//from   w  w  w  .j  ava 2 s .  com

    String uri = method.getURI().toString();
    String statusText = method.getStatusLine() != null ? method.getStatusLine().getReasonPhrase() : null;
    Map<String, String> headers = extractResponseHeaders(method.getResponseHeaders());

    Object responseBody = extractResponseBody(method, exchange);
    if (transferException && responseBody != null && responseBody instanceof Exception) {
        // if the response was a serialized exception then use that
        return (Exception) responseBody;
    }

    // make a defensive copy of the response body in the exception so its detached from the cache
    String copy = null;
    if (responseBody != null) {
        copy = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, responseBody);
    }

    if (responseCode >= 300 && responseCode < 400) {
        String redirectLocation;
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
            answer = new HttpOperationFailedException(uri, responseCode, statusText, redirectLocation, headers,
                    copy);
        } else {
            // no redirect location
            answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy);
        }
    } else {
        // internal server error (error code 500)
        answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy);
    }

    return answer;
}

From source file:org.apache.cloudstack.network.element.SspClient.java

private String executeMethod(HttpMethod method) {
    String apiCallPath = null;//from  w  w  w  .j  a v  a2s .  c o m
    try {
        apiCallPath = method.getName() + " " + method.getURI().toString();
    } catch (URIException e) {
        s_logger.error("method getURI failed", e);
    }

    String response = null;
    try {
        client.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (HttpException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } catch (IOException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } finally {
        method.releaseConnection();
    }

    if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        if (!login()) {
            return null;
        }

        try {
            client.executeMethod(method);
            response = method.getResponseBodyAsString();
        } catch (HttpException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } catch (IOException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } finally {
            method.releaseConnection();
        }
    }
    s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine());
    if (method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
        RequestEntity reqEntity = emethod.getRequestEntity();
        if (reqEntity instanceof StringRequestEntity) {
            StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity;
            s_logger.debug("ssp api request body:" + strReqEntity.getContent());
        } else {
            s_logger.debug("ssp api request body:" + emethod.getRequestEntity());
        }
    }
    s_logger.debug("ssp api response body:" + response);
    return response;
}

From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java

/**
 * Forwards the request and returns the response.
 * /*w  w w . j av  a 2  s  .  c  o  m*/
 * The rest is probably out of date:
 * Will use a UrlGetMethod to benefit the cacheing mechanism
 * and intermediate proxy servers.
 * It is potentially possible that the size of the request
 * may grow beyond a certain limit for GET and it will require POST instead.
 *
 * @return byte[] XML response
 */
public byte[] fetch() throws ProcessingException {
    HttpMethod method = null;

    // check which method (GET or POST) to use.
    if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) {
        method = new PostMethod(this.source);
    } else {
        method = new GetMethod(this.source);
    }

    if (this.getLogger().isDebugEnabled()) {
        this.getLogger().debug("request HTTP method: " + method.getName());
    }

    // this should probably be exposed as a sitemap option
    method.setFollowRedirects(true);

    // copy request parameters and merge with URL parameters
    Request request = ObjectModelHelper.getRequest(objectModel);

    ArrayList paramList = new ArrayList();
    Enumeration enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String pname = (String) enumeration.nextElement();
        String[] paramsForName = request.getParameterValues(pname);
        for (int i = 0; i < paramsForName.length; i++) {
            NameValuePair pair = new NameValuePair(pname, paramsForName[i]);
            paramList.add(pair);
        }
    }

    if (paramList.size() > 0) {
        NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()];
        paramList.toArray(allSubmitParams);

        String urlQryString = method.getQueryString();

        // use HttpClient encoding routines
        method.setQueryString(allSubmitParams);
        String submitQryString = method.getQueryString();

        // set final web service query string

        // sometimes the querystring is null here...
        if (null == urlQryString) {
            method.setQueryString(submitQryString);
        } else {
            method.setQueryString(urlQryString + "&" + submitQryString);
        }

    } // if there are submit parameters

    byte[] response = null;
    try {
        int httpStatus = httpClient.executeMethod(method);
        if (httpStatus < 400) {
            if (this.getLogger().isDebugEnabled()) {
                this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus);
            }
        } else {
            throw new ProcessingException("The remote returned error " + httpStatus
                    + " when attempting to access remote URL:" + method.getURI());
        }
    } catch (URIException e) {
        throw new ProcessingException("There is a problem with the URI: " + this.source, e);
    } catch (IOException e) {
        try {
            throw new ProcessingException(
                    "Exception when attempting to access the remote URL: " + method.getURI(), e);
        } catch (URIException ue) {
            throw new ProcessingException("There is a problem with the URI: " + this.source, ue);
        }
    } finally {
        /* It is important to always read the entire response and release the
         * connection regardless of whether the server returned an error or not.
         * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html}
         */
        response = method.getResponseBody();
        method.releaseConnection();
    }

    return response;
}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }//from w  ww . java2 s .co  m
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java

/**
 * Does a basic HTTP GET and returns Http Status code + response body
 * Will add the dummy user query string/*  w  w  w. j  a  va2 s. c om*/
 */
private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data,
        NameValuePair[] params) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod method;
    switch (type) {
    case GET:
        method = new GetMethod(uri);
        break;
    case DELETE:
        method = new DeleteMethod(uri);
        break;
    case PUT:
        method = new PutMethod(uri);
        if (data == null) {
            break;
        }
        String msgBody = JsonBuilder.mapToJson(data);
        LOG.info("Msg Body: " + msgBody);
        StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet);
        ((PutMethod) method).setRequestEntity(sre);
        break;
    default:
        throw new IllegalArgumentException("Unsupported method type: " + type);
    }
    if (params == null) {
        method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) });
    } else {
        NameValuePair[] newParams = new NameValuePair[params.length + 1];
        System.arraycopy(params, 0, newParams, 1, params.length);
        newParams[0] = new NameValuePair("user.name", username);
        method.setQueryString(newParams);
    }
    String actualUri = "no URI";
    try {
        actualUri = method.getURI().toString();//should this be escaped string?
        LOG.debug(type + ": " + method.getURI().getEscapedURI());
        int httpStatus = client.executeMethod(method);
        LOG.debug("Http Status Code=" + httpStatus);
        String resp = method.getResponseBodyAsString();
        LOG.debug("response: " + resp);
        return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName());
    } catch (IOException ex) {
        LOG.error("doHttpCall() failed", ex);
    } finally {
        method.releaseConnection();
    }
    return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri,
            method.getName());
}

From source file:org.apache.jmeter.protocol.http.control.CacheManager.java

/**
 * Save the Last-Modified, Etag, and Expires headers if the result is
 * cacheable. Version for Commons HttpClient implementation.
 *
 * @param method/* w ww . jav  a 2  s  . c o  m*/
 *            {@link HttpMethod} to get header information from
 * @param res
 *            result to decide if result is cacheable
 * @throws URIException
 *             if extraction of the the uri from <code>method</code> fails
 * @deprecated HC3.1 will be dropped in upcoming version
 */
@Deprecated
public void saveDetails(HttpMethod method, HTTPSampleResult res) throws URIException {
    if (isCacheable(res) && !hasVaryHeader(method)) {
        String lastModified = getHeader(method, HTTPConstants.LAST_MODIFIED);
        String expires = getHeader(method, HTTPConstants.EXPIRES);
        String etag = getHeader(method, HTTPConstants.ETAG);
        String url = method.getURI().toString();
        String cacheControl = getHeader(method, HTTPConstants.CACHE_CONTROL);
        String date = getHeader(method, HTTPConstants.DATE);
        setCache(lastModified, cacheControl, expires, etag, url, date);
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpExternalService.java

public void invoke(PartnerRoleMessageExchange odeMex) {
    if (log.isDebugEnabled())
        log.debug("Preparing " + getClass().getSimpleName() + " invocation...");
    try {// w  ww .j a v a2 s. c  om
        // note: don't make this map an instance attribute, so we always get the latest version
        final Map<String, String> properties = pconf.getEndpointProperties(endpointReference);
        final HttpParams params = Properties.HttpClient.translate(properties);

        // base baseUrl
        String mexEndpointUrl = ((MutableEndpoint) odeMex.getEndpointReference()).getUrl();
        String baseUrl = mexEndpointUrl;
        // The endpoint URL might be overridden from the properties file(s)
        // The order of precedence is (in descending order): process, property, wsdl.
        if (endpointUrl.equals(new URL(mexEndpointUrl))) {
            String address = (String) params.getParameter(Properties.PROP_ADDRESS);
            if (address != null) {
                if (log.isDebugEnabled())
                    log.debug(
                            "Endpoint URL overridden by property files. " + mexEndpointUrl + " => " + address);
                baseUrl = address;
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Endpoint URL overridden by process. " + endpointUrl + " => " + mexEndpointUrl);
        }

        baseUrl = clusterUrlTransformer.rewriteOutgoingClusterURL(baseUrl);

        // build the http method
        final HttpMethod method = httpMethodConverter.createHttpRequest(odeMex, params, baseUrl);

        // create a client
        HttpClient client = new HttpClient(connections);

        // configure the client (proxy, security, etc)
        Element message = odeMex.getRequest().getMessage();
        Element authenticatePart = message == null ? null
                : DOMUtils.findChildByName(message, new QName(null, "WWW-Authenticate"));
        HttpHelper.configure(client, method.getURI(), authenticatePart, params);

        // this callable encapsulates the http method execution and the process of the response
        final Callable executionCallable;

        // execute it
        boolean isTwoWay = odeMex
                .getMessageExchangePattern() == MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
        if (isTwoWay) {
            // two way
            executionCallable = new HttpExternalService.TwoWayCallable(client, method,
                    odeMex.getMessageExchangeId(), odeMex.getOperation());
            scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
                public void afterCompletion(boolean success) {
                    // If the TX is rolled back, then we don't send the request.
                    if (!success)
                        return;
                    // The invocation must happen in a separate thread
                    executorService.submit(executionCallable);
                }

                public void beforeCompletion() {
                }
            });
            odeMex.replyAsync();
        } else {
            // one way, just execute and forget
            executionCallable = new HttpExternalService.OneWayCallable(client, method,
                    odeMex.getMessageExchangeId(), odeMex.getOperation());
            executorService.submit(executionCallable);
            odeMex.replyOneWayOk();
        }
    } catch (UnsupportedEncodingException e) {
        String errmsg = "The returned HTTP encoding isn't supported " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
    } catch (URIException e) {
        String errmsg = "Error sending message to " + getClass().getSimpleName() + " for ODE mex " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
    } catch (Exception e) {
        String errmsg = "Unknown HTTP call error for ODE mex " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static String requestToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {/*from   w  w w  .j  av a  2  s  . co m*/
        sb.append("HTTP Request Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nRequest Headers:");
    Header[] headers = m.getRequestHeaders();
    if (headers.length == 0)
        sb.append(" n/a");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    if (m instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) m;
        if (eem.getRequestEntity() != null) {
            sb.append("\nRequest Entity:");
            sb.append("\n\tContent-Type:").append(eem.getRequestEntity().getContentType());
            sb.append("\n\tContent-Length:").append(eem.getRequestEntity().getContentLength());
            if (eem.getRequestEntity() instanceof StringRequestEntity) {
                StringRequestEntity sre = (StringRequestEntity) eem.getRequestEntity();
                sb.append("\n\tContent-Charset:").append(sre.getCharset());
                sb.append("\n\tRequest Entity:\n").append(sre.getContent());
            }
        }
    }
    return sb.toString();
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static String responseToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {/*from w ww .  j a  va2  s .  c o  m*/
        sb.append("HTTP Response Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nStatus-Line: ").append(m.getStatusLine());
    Header[] headers = m.getResponseHeaders();
    if (headers.length != 0)
        sb.append("\nResponse Headers: ");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    try {
        if (StringUtils.isNotEmpty(m.getResponseBodyAsString())) {
            sb.append("\nResponse Entity:\n").append(m.getResponseBodyAsString());
        }
    } catch (IOException e) {
        log.error(e);
    }
    Header[] footers = m.getResponseFooters();
    if (footers.length != 0)
        sb.append("\nResponse Footers: ");
    for (int i = 0; i < footers.length; i++) {
        Header h = footers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    return sb.toString();
}