Example usage for org.apache.commons.httpclient HttpMethodBase getResponseHeader

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getResponseHeader.

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

/**
 * Collect the HTTP header information and set them in the message context
 *
 * @param method HttpMethodBase from which to get information
 * @param msgContext the MessageContext in which to place the information... OR NOT!
 * @throws AxisFault if problems occur/*w w w  .  ja va  2  s . co  m*/
 */
protected void obtainHTTPHeaderInformation(HttpMethodBase method, MessageContext msgContext) throws AxisFault {
    // Set RESPONSE properties onto the REQUEST message context.  They will need to be copied off the request context onto
    // the response context elsewhere, for example in the OutInOperationClient.
    Map transportHeaders = new CommonsTransportHeaders(method.getResponseHeaders());
    msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders);
    msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode()));
    Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);

    if (header != null) {
        HeaderElement[] headers = header.getElements();
        MessageContext inMessageContext = msgContext.getOperationContext()
                .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

        Object contentType = header.getValue();
        Object charSetEnc = null;

        for (int i = 0; i < headers.length; i++) {
            NameValuePair charsetEnc = headers[i].getParameterByName(HTTPConstants.CHAR_SET_ENCODING);
            if (charsetEnc != null) {
                charSetEnc = charsetEnc.getValue();
            }
        }

        if (inMessageContext != null) {
            inMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
            inMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        } else {

            // Transport details will be stored in a HashMap so that anybody interested can
            // retrieve them
            HashMap transportInfoMap = new HashMap();
            transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType);
            transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);

            //the HashMap is stored in the outgoing message.
            msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP, transportInfoMap);
        }
    }

    String sessionCookie = null;
    // Process old style headers first
    Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE);
    String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID);
    // process all the cookieHeaders, when load balancer is fronted it may require some cookies to function.
    sessionCookie = processCookieHeaders(cookieHeaders);

    // Overwrite old style cookies with new style ones if present
    cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2);
    for (int i = 0; i < cookieHeaders.length; i++) {
        HeaderElement[] elements = cookieHeaders[i].getElements();
        for (int e = 0; e < elements.length; e++) {
            HeaderElement element = elements[e];
            if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName())
                    || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) {
                sessionCookie = processCookieHeader(element);
            }
            if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) {
                sessionCookie = processCookieHeader(element);
            }
        }
    }

    if (sessionCookie != null && !sessionCookie.isEmpty()) {
        msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie);
    }
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

protected void processResponse(HttpMethodBase httpMethod, MessageContext msgContext) throws IOException {
    obtainHTTPHeaderInformation(httpMethod, msgContext);

    InputStream in = httpMethod.getResponseBodyAsStream();
    if (in == null) {
        throw new AxisFault(Messages.getMessage("canNotBeNull", "InputStream"));
    }//from w  w  w.  j  a  v  a  2  s  .c o  m
    Header contentEncoding = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
    if (contentEncoding != null) {
        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
            in = new GZIPInputStream(in);
            // If the content-encoding is identity we can basically ignore it.
        } else if (!"identity".equalsIgnoreCase(contentEncoding.getValue())) {
            throw new AxisFault(
                    "HTTP :" + "unsupported content-encoding of '" + contentEncoding.getValue() + "' found");
        }
    }

    OperationContext opContext = msgContext.getOperationContext();
    if (opContext != null) {
        opContext.setProperty(MessageContext.TRANSPORT_IN, in);
    }
}

From source file:org.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to handle the HTTP Response//from www .j  ava  2  s  .  co m
 *
 * @param msgContext - The MessageContext of the message
 * @param method     - The HTTP method used
 * @throws IOException - Thrown in case an exception occurs
 */
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException {
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    Set<Integer> nonErrorCodes = (Set<Integer>) msgContext
            .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES);
    Set<Integer> errorCodes = new HashSet<Integer>();
    String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing
    // ESBJAVA-3178
    if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) {
        for (String strRetryErrorCode : strRetryErrorCodes.split(",")) {
            try {
                errorCodes.add(Integer.valueOf(strRetryErrorCode));
            } catch (NumberFormatException e) {
                log.warn(strRetryErrorCode + " is not a valid status code");
            }
        }
    }
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
            || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) {
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
        return;
    } else {
        // Since we don't process the response, we must release the connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * Used to handle the HTTP Response// www  .  ja  va 2 s  . c  o m
 * 
 * @param msgContext
 *            - The MessageContext of the message
 * @param method
 *            - The HTTP method used
 * @throws IOException
 *             - Thrown in case an exception occurs
 */
protected void handleResponse(MessageContext msgContext, Object httpMethodBase) throws IOException {
    HttpMethodBase method;
    if (httpMethodBase instanceof HttpMethodBase) {
        method = (HttpMethodBase) httpMethodBase;
    } else {
        log.trace("HttpMethodBase expected, but found - " + httpMethodBase);
        return;
    }
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_BAD_REQUEST) {
        // Save the HttpMethod so that we can release the connection when
        // cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else {
        // Since we don't process the response, we must release the
        // connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

protected void processResponse(HttpMethodBase httpMethod, MessageContext msgContext) throws IOException {
    obtainHTTPHeaderInformation(httpMethod, msgContext);

    InputStream in = httpMethod.getResponseBodyAsStream();
    if (in == null) {
        throw new AxisFault(Messages.getMessage("canNotBeNull", "InputStream"));
    }/*  ww w  . j a  v  a  2  s  .  c om*/
    Header contentEncoding = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
    if (contentEncoding != null) {
        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
            in = new GZIPInputStream(in);
            // If the content-encoding is identity we can basically ignore
            // it.
        } else if (!"identity".equalsIgnoreCase(contentEncoding.getValue())) {
            throw new AxisFault(
                    "HTTP :" + "unsupported content-encoding of '" + contentEncoding.getValue() + "' found");
        }
    }

    OperationContext opContext = msgContext.getOperationContext();
    if (opContext != null) {
        opContext.setProperty(MessageContext.TRANSPORT_IN, in);
    }
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.Action.java

private String responseToErrorMessage(final HttpMethodBase method) {
    assert method.isRequestSent() : "no use getting an error message unless the request is sent";

    final Header contentTypeHeader = method.getResponseHeader(CONTENT_TYPE);
    if (contentTypeHeader != null && TEXT_HTML_CONTENT_TYPE.equals(contentTypeHeader.getValue())) {
        // The error message is the response content
        // Safety margin of 1024 characters, anything longer is probably
        // useless and will clutter the logs
        try {/*from w ww  .j a  va  2s  .c om*/
            return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
        } catch (IOException e) {
            s_logger.debug("Error while loading response body", e);
        }
    }

    // The default
    return method.getStatusText();
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

private long getLastModified(HttpMethodBase method) {
    Header header = method.getResponseHeader("last-modified");
    if (header != null) {
        String lastModified = header.getValue();
        try {//ww w .j a v  a 2 s .  c om
            return LAST_MODIFIED_FORMAT.parse(lastModified).getTime();
        } catch (ParseException e) {
            // ignored
        }
        return System.currentTimeMillis();
    } else {
        return System.currentTimeMillis();
    }
}

From source file:org.apache.jetspeed.portlets.sso.SSOTicketPortlet.java

private String requestTicket(String url, RenderRequest request, RenderResponse response) {
    // ...set up URL and HttpClient stuff
    String ticket = "";
    HttpClient client = new HttpClient();
    HttpMethodBase httpMethod = null;
    httpMethod = new PostMethod();
    //String useragentProperty = request.getProperty("User-Agent");
    httpMethod.addRequestHeader("User-Agent", "Firefox");
    httpMethod.setPath(url);/*w w w .j  a v a2 s. co m*/
    try {
        client.executeMethod(httpMethod);
        int responseCode = httpMethod.getStatusCode();
        if (responseCode >= 300 && responseCode <= 399) {
            // redirection that could not be handled automatically!!! (probably from a POST)
            Header locationHeader = httpMethod.getResponseHeader("location");
            String redirectLocation = locationHeader != null ? locationHeader.getValue() : null;
            if (redirectLocation != null) {
                // one more time (assume most params are already encoded & new URL is using GET protocol!)
                return requestTicket(redirectLocation, null, null);
            } else {
                // The response is a redirect, but did not provide the new location for the resource.
                throw new PortletException(
                        "Redirection code: " + responseCode + ", but with no redirectionLocation set.");
            }
        } else if (responseCode == 200) {
            //           String body = httpMethod.getResponseBodyAsString();
            //           Header [] head =  httpMethod.getResponseHeaders();
            TicketParamRewriter ticketWriter = new TicketParamRewriter();
            String ticketName = (String) request.getPreferences().getValue(SSO_PREF_TICKET_NAME, null);
            if (ticketName != null) {
                ticketWriter.setTicketName(ticketName);
                Reader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
                createParserAdaptor().parse(ticketWriter, reader);
                ticket = ticketWriter.getTicket();
            }
        }
    } catch (Exception e) {
        logger.error("Unexpected error during request ticket.", e);
    }
    return ticket;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate.//from ww  w .  j  a va 2s. co  m
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 *
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + urlStr);
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }

    HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.setURL(url);

    res.sampleStart(); // Count the retries as well in the time
    try {
        // May generate IllegalArgumentException
        if (method.equals(HTTPConstants.POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(HTTPConstants.GET)) {
            httpMethod = new GetMethod(urlStr);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.DELETE;
                }
            };
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.PATCH;
                }
            };
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }

        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
            if (cacheManager.inCache(url)) {
                return updateSampleResultForResourceInCache(res);
            }
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);

        // Setup connection
        HttpClient client = setupConnection(url, httpMethod, res);
        savedClient = client;

        // Handle the various methods
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData((PostMethod) httpMethod);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                || method.equals(HTTPConstants.DELETE)) {
            String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
            res.setQueryString(putBody);
        }

        int statusCode = client.executeMethod(httpMethod);

        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
        if (localAddr != null) {
            httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        // Needs to be done after execute to pick up all the headers
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        // Request sent. Now get the response:
        InputStream instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD
            instream = new CountingInputStream(instream);
            try {
                Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                    InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                    res.setResponseData(
                            readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));
                } else {
                    res.setResponseData(
                            readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                }
            } finally {
                JOrphanUtils.closeQuietly(instream);
            }
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header");
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation); // in case sanitising fails
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        if (instream != null) {
            res.setBodySize(((CountingInputStream) instream).getCount());
        }
        res.setHeadersSize(calculateHeadersSize(httpMethod));
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample");
        return res;
    } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod can be null if method is unexpected
        if (httpMethod != null) {
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
        }
        errorResult(e, res);
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod cannot be null here, otherwise 
        // it would have been caught in the previous catch block
        res.setRequestHeaders(getConnectionHeaders(httpMethod));
        errorResult(e, res);
        return res;
    } finally {
        savedClient = null;
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate./* w w  w.  j av a  2  s  . co m*/
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 * 
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toExternalForm();

    // Check if this is an entity-enclosing method
    boolean isPost = method.equals(POST) || method.equals(PUT);

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    // Handles OAuth signing
    try {
        message = getOAuthMessage(url, method);

        urlStr = message.URL;

        if (isPost) {
            urlStr = message.URL;
        } else {
            if (useAuthHeader)
                urlStr = OAuth.addParameters(message.URL, nonOAuthParams);
            else
                urlStr = OAuth.addParameters(message.URL, message.getParameters());
        }
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (OAuthException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (URISyntaxException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    }

    log.debug("Start : sample " + urlStr); //$NON-NLS-1$
    log.debug("method " + method); //$NON-NLS-1$

    HttpMethodBase httpMethod = null;
    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.sampleStart(); // Count the retries as well in the time
    HttpClient client = null;
    InputStream instream = null;

    try {
        // May generate IllegalArgumentException
        if (method.equals(POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(DELETE)) {
            httpMethod = new DeleteMethod(urlStr);
        } else if (method.equals(GET)) {
            httpMethod = new GetMethod(urlStr);
        } else {
            log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$
            httpMethod = new GetMethod(urlStr);
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);
        // Setup connection
        client = setupConnection(new URL(urlStr), httpMethod, res);
        // Handle POST and PUT
        if (isPost) {
            String postBody = sendPostData(httpMethod);
            res.setQueryString(postBody);
        }

        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = client.executeMethod(httpMethod);

        // Request sent. Now get the response:
        instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$
            }
            res.setRedirectLocation(headerLocation.getValue());
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample"); //$NON-NLS-1$
        httpMethod.releaseConnection();
        return res;
    } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
    {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}