Example usage for org.apache.commons.httpclient Header Header

List of usage examples for org.apache.commons.httpclient Header Header

Introduction

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

Prototype

public Header(String paramString1, String paramString2) 

Source Link

Usage

From source file:org.mule.transport.http.transformers.MuleMessageToHttpResponse.java

@Override
public Object transformMessage(MuleMessage msg, String outputEncoding) throws TransformerException {
    Object src = msg.getPayload();

    // Note this transformer excepts Null as we must always return a result
    // from the Http
    // connector if a response transformer is present
    if (src instanceof NullPayload) {
        src = StringUtils.EMPTY;/*from   w  w w .jav  a 2 s  .co  m*/
    }

    try {
        HttpResponse response;
        if (src instanceof HttpResponse) {
            response = (HttpResponse) src;
        } else {
            response = createResponse(src, outputEncoding, msg);
        }

        // Ensure there's a content type header
        if (!response.containsHeader(HttpConstants.HEADER_CONTENT_TYPE)) {
            response.addHeader(
                    new Header(HttpConstants.HEADER_CONTENT_TYPE, HttpConstants.DEFAULT_CONTENT_TYPE));
        }

        // Ensure there's a content length or transfer encoding header
        if (!response.containsHeader(HttpConstants.HEADER_CONTENT_LENGTH)
                && !response.containsHeader(HttpConstants.HEADER_TRANSFER_ENCODING)) {
            if (response.hasBody()) {
                long len = response.getContentLength();
                if (len < 0) {
                    if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) {
                        // Ensure that we convert the payload to an in memory representation
                        // so we don't end up with a chunked response
                        len = msg.getPayloadAsBytes().length;

                        response.setBody(msg);

                        Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, Long.toString(len));
                        response.setHeader(header);
                    } else {
                        Header header = new Header(HttpConstants.HEADER_TRANSFER_ENCODING, "chunked");
                        response.addHeader(header);
                    }
                } else {
                    Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, Long.toString(len));
                    response.setHeader(header);
                }
            } else {
                Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, "0");
                response.addHeader(header);
            }
        }

        // See if the the client explicitly handles connection persistence
        String connHeader = msg.getOutboundProperty(HttpConstants.HEADER_CONNECTION);
        if (connHeader != null) {
            if (connHeader.equalsIgnoreCase("keep-alive")) {
                response.setKeepAlive(true);
            }
            if (connHeader.equalsIgnoreCase("close")) {
                response.setKeepAlive(false);
            }
        }

        final String method = msg.getOutboundProperty(HttpConnector.HTTP_METHOD_PROPERTY);
        if ("HEAD".equalsIgnoreCase(method)) {
            // this is a head request, we don't want to send the actual content
            response.setBody((MuleMessage) null);
        }
        return response;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

}

From source file:org.mule.transport.http.transformers.MuleMessageToHttpResponse.java

protected HttpResponse createResponse(Object src, String encoding, MuleMessage msg)
        throws IOException, TransformerException {
    HttpResponse response = new HttpResponse();

    Object tmp = msg.getOutboundProperty(HttpConnector.HTTP_STATUS_PROPERTY);
    int status = HttpConstants.SC_OK;

    if (tmp != null) {
        status = Integer.valueOf(tmp.toString());
    } else if (msg.getExceptionPayload() != null) {
        status = HttpConstants.SC_INTERNAL_SERVER_ERROR;
    }//from   w w w. ja  v a 2  s  .  c o  m

    String version = msg.getInboundProperty(HttpConnector.HTTP_VERSION_PROPERTY);
    if (version == null) {
        version = HttpConstants.HTTP11;
    }

    String contentType = msg.getInboundProperty(HttpConstants.HEADER_CONTENT_TYPE);
    if (contentType == null) {
        contentType = msg.getInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE);
    }

    // MULE-4047 Don't explicitly set the content-type to a default value here,
    // otherwise any settings on the servlet/transport will be happily ignored.
    //if (contentType == null)
    //{
    //    contentType = HttpConstants.DEFAULT_CONTENT_TYPE;
    //
    //    if (encoding != null)
    //    {
    //        contentType += "; charset=" + encoding;
    //    }
    //    logger.warn("Content-Type was not set, defaulting to: " + contentType);
    //}

    response.setStatusLine(HttpVersion.parse(version), status);
    if (contentType != null) {
        response.setHeader(new Header(HttpConstants.HEADER_CONTENT_TYPE, contentType));
    }
    String date = formatDate(System.currentTimeMillis());
    response.setHeader(new Header(HttpConstants.HEADER_DATE, date));
    response.setHeader(new Header(HttpConstants.HEADER_SERVER, server));

    String etag = msg.getOutboundProperty(HttpConstants.HEADER_ETAG);
    if (etag != null) {
        response.setHeader(new Header(HttpConstants.HEADER_ETAG, etag));
    }
    response.setFallbackCharset(encoding);

    Collection<String> headerNames = new LinkedList<String>();
    headerNames.addAll(HttpConstants.RESPONSE_HEADER_NAMES.values());
    headerNames.addAll(HttpConstants.GENERAL_AND_ENTITY_HEADER_NAMES.values());

    for (String headerName : headerNames) {
        if (HttpConstants.HEADER_COOKIE_SET.equals(headerName)) {
            // TODO This have to be improved. We shouldn't have to look in all
            // scopes
            Object cookiesObject = msg.getInvocationProperty(headerName);
            if (cookiesObject == null) {
                cookiesObject = msg.getOutboundProperty(headerName);
            }
            if (cookiesObject == null) {
                cookiesObject = msg.getInboundProperty(headerName);
            }
            if (cookiesObject == null) {
                continue;
            }

            if (!(cookiesObject instanceof Cookie[])) {
                response.addHeader(new Header(headerName, cookiesObject.toString()));
            } else {
                Cookie[] arrayOfCookies = CookieHelper.asArrayOfCookies(cookiesObject);
                for (Cookie cookie : arrayOfCookies) {
                    response.addHeader(
                            new Header(headerName, CookieHelper.formatCookieForASetCookieHeader(cookie)));
                }
            }
        } else {
            Object value = msg.getInvocationProperty(headerName);
            if (value == null) {
                value = msg.getOutboundProperty(headerName);
            }
            if (value != null) {
                response.setHeader(new Header(headerName, value.toString()));
            }
        }
    }

    Map customHeaders = msg.getOutboundProperty(HttpConnector.HTTP_CUSTOM_HEADERS_MAP_PROPERTY);
    if (customHeaders != null) {
        throw new TransformerException(HttpMessages.customHeaderMapDeprecated(), this);
    }

    //attach the outbound properties to the message
    for (String headerName : msg.getOutboundPropertyNames()) {
        if (response.getFirstHeader(headerName) != null) {
            //keep headers already set
            continue;
        }
        Object v = msg.getOutboundProperty(headerName);
        if (v != null) {
            if (headerName.startsWith(MuleProperties.PROPERTY_PREFIX)) {
                headerName = HttpConstants.CUSTOM_HEADER_PREFIX + headerName;
            }
            response.setHeader(new Header(headerName, v.toString()));
        }
    }

    if (msg.getCorrelationId() != null) {
        response.setHeader(
                new Header(HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_ID_PROPERTY,
                        msg.getCorrelationId()));
        response.setHeader(new Header(
                HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_GROUP_SIZE_PROPERTY,
                String.valueOf(msg.getCorrelationGroupSize())));
        response.setHeader(new Header(
                HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_SEQUENCE_PROPERTY,
                String.valueOf(msg.getCorrelationSequence())));
    }
    if (msg.getReplyTo() != null) {
        response.setHeader(
                new Header(HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_REPLY_TO_PROPERTY,
                        msg.getReplyTo().toString()));
    }

    try {
        response.setBody(msg);
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

    return response;
}

From source file:org.mule.transport.servlet.MuleReceiverServletTestCase.java

@Test
public void responseWithSingleValueForHeaderShouldWriteSingleValueToServletResponse() throws Exception {
    String headerValue = "value";

    HttpResponse httpResponse = new HttpResponse();
    httpResponse.addHeader(new Header(KEY, headerValue));

    HttpServletResponse servletResponse = createServletResponseAndWriteResponse(httpResponse);
    verify(servletResponse).addHeader(KEY, headerValue);
}

From source file:org.mule.transport.servlet.MuleReceiverServletTestCase.java

@Test
public void responseWithMultipleValuesForHeaderShouldWriteMultipleValuesToServletResponse() throws Exception {
    String firstValue = "value1";
    String secondValue = "value2";

    HttpResponse httpResponse = new HttpResponse();
    httpResponse.addHeader(new Header(KEY, firstValue));
    httpResponse.addHeader(new Header(KEY, secondValue));

    HttpServletResponse servletResponse = createServletResponseAndWriteResponse(httpResponse);
    verify(servletResponse).addHeader(KEY, firstValue);
    verify(servletResponse).addHeader(KEY, secondValue);
}

From source file:org.mule.transport.servlet.MuleReceiverServletTestCase.java

@Test
public void responseWithExistingContentTypeHeaderShouldPreserve() throws Exception {
    String contentType = "foo/bar";

    HttpResponse httpResponse = new HttpResponse();
    httpResponse.addHeader(new Header(HttpConstants.HEADER_CONTENT_TYPE, contentType));

    HttpServletResponse servletResponse = createServletResponseAndWriteResponse(httpResponse);
    verify(servletResponse).setContentType(contentType);
}

From source file:org.na.WebHelper.java

public String download(JiraCfgDto cfg) throws HttpException, IOException {

    PostMethod post = new PostMethod(cfg.getJiraUrl() + "/login.jsp");
    post.setRequestHeader(new Header("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1"));
    setCedentials(cfg, post);/*from w  w  w . j a va 2s.c  o  m*/
    if (authorisation) {
        httpClient.executeMethod(post);
        post.setFollowRedirects(false);
        Header header = post.getResponseHeader("Set-Cookie");
        sessionId = header.getElements()[0].getValue();
        log.info("SessionId: " + sessionId);
    }

    String xlsStream = cfg.getJiraUrl()
            + "/sr/jira.issueviews:searchrequest-excel-all-fields/temp/SearchRequest.xls?jqlQuery="
            + encodeUrl(cfg.getJiraQuery()) + "&tempMax=" + cfg.getJiraTmpMax();
    GetMethod get = new GetMethod(xlsStream);
    get.setRequestHeader(new Header("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1"));
    if (authorisation) {
        get.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
    }
    httpClient.executeMethod(get);

    String body = get.getResponseBodyAsString();
    verifyOutput(body);
    return body;
}

From source file:org.nlp2rdf.implementation.spotlight.SpotlightWrapper.java

public Hashtable<String, List<String>> querySpotlight(String context) {
    // String context =
    // "Hong Kong (CNN) -- A week into paralyzing pro-democracy protests in Hong Kong, authorities and demonstrators are still at loggerheads. Both sides say they are open to talks, but each wants concessions from the other. A student group said Sunday that it would restart dialogue with the government if police do a better job of handling clashes between pro-democracy protesters and people opposed to the demonstrations. The protesters, many of them students, have blocked major highways in several key districts for the past week, challenging a decision by Beijing about how elections will work in the semiautonomous Chinese territory.";

    log.info("Querying API.");
    log.info(/*from  ww w.  j  av a 2  s .  c  o  m*/
            "This service uses the paper: Improving Efficiency and Accuracy in Multilingual Entity Extraction, from Joachim Daiber and Max Jakob and Chris Hokamp and Pablo N. Mendes. More information can be found here: https://github.com/dbpedia-spotlight/dbpedia-spotlight/wiki/Citation#statistical");

    HttpClient client = new HttpClient();

    try {
        GetMethod getMethod = new GetMethod(spotlightAPI + "rest/candidates?" + "confidence=" + confidence
                + "&support=" + support + "&policy=" + policy + "&disambiguator=" + disambiguator + "&text="
                + URLEncoder.encode(context, "utf-8"));
        getMethod.addRequestHeader(new Header("Accept", "application/json"));

        // Execute the method.
        int statusCode = client.executeMethod(getMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = getMethod.getResponseBody();

        JSONObject j = new JSONObject(new String(responseBody));
        // System.out.println(j);
        JSONObject annotation = new JSONObject(j.getJSONObject("annotation").toString());
        // System.out.println(annotation);

        // check if is only one object
        boolean isArray = true;
        try {
            JSONObject surface = annotation.getJSONObject("surfaceForm");
            isArray = false;
            String key = surface.getString("@offset");
            String value = surface.getJSONObject("resource").get("@uri").toString();
            List<String> value2 = new ArrayList<String>();
            value2.add(value);

            // log.info("Adding value "+value+" for offset "+key);
            h.put(key, value2);

        } catch (Exception e) {
            e.getMessage();
        }

        if (isArray) {
            JSONArray surface = annotation.getJSONArray("surfaceForm");
            try {
                JSONArray resultJSON = new JSONArray(surface.toString());
                // System.out.println(resultJSON);
                for (int i = 0; i < resultJSON.length(); i++) {
                    try {
                        JSONObject entity = resultJSON.getJSONObject(i);

                        // check if is an array of entities
                        isArray = false;
                        try {
                            JSONArray resources = entity.getJSONArray("resource");
                            isArray = true;
                            List<String> value2 = new ArrayList<String>();
                            for (int k = 0; k < resources.length(); k++) {
                                JSONObject entity2 = resources.getJSONObject(k);
                                // System.out.println("----" + entity2);
                                String key = entity.getString("@offset");
                                String value = entity2.getString("@uri");
                                // log.info("Adding value "+value+" for offset "+key);
                                value2.add(value);
                                h.put(key, value2);
                            }
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }

                        // if there is only one entity
                        if (!isArray) {
                            String key = entity.getString("@offset");
                            String value = entity.getJSONObject("resource").get("@uri").toString();

                            List<String> value2 = new ArrayList<String>();
                            value2.add(value);
                            h.put(key, value2);
                        }

                    } catch (JSONException e) {
                        System.out.println("JSON exception " + e);
                    }
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return h;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * /*from w ww.java2s. c  om*/
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Send a command to the Particle REST API (convenience function).
 *
 * @param device/*from  w  w  w .  j  a  v  a 2 s.  c  o m*/
 *            the device context, or <code>null</code> if not needed for this command.
 * @param funcName
 *            the function name to call, or variable/field to retrieve if <code>command</code> is
 *            <code>null</code>.
 * @param user
 *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param pass
 *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param command
 *            the command to send to the API.
 * @param proc
 *            a callback object that receives the status code and response body, or <code>null</code> if not
 *            needed.
 */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command,
        HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);

    switch (funcName) {
    case "createToken":
        httpMethod = HTTP_POST;
        url = TOKEN_URL;
        content = command;
        contentType = APPLICATION_FORM_URLENCODED;
        break;
    case "deleteToken":
        httpMethod = HTTP_DELETE;
        url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
        break;
    case "getDevices":
        httpMethod = HTTP_GET;
        url = String.format(GET_DEVICES_URL, tokens.accessToken);
        break;
    default:
        url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
        if (command == null) {
            // retrieve a variable
            httpMethod = HTTP_GET;
        } else {
            // call a function
            httpMethod = HTTP_POST;
            content = command;
            contentType = APPLICATION_JSON;
        }
        break;
    }

    HttpClient client = new HttpClient();

    // Only perform basic authentication when we aren't using OAuth

    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }

    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }

        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }

        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }

        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
 * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
 * //w  w  w.j  a va2  s .  co m
 * @param httpMethod
 *            the HTTP method to use
 * @param url
 *            the url to execute (in milliseconds)
 * @param contentString
 *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
 *            sent.
 * @param contentType
 *            the content type of the given <code>contentString</code>
 * @return the response body or <code>NULL</code> when the request went wrong
 */
protected final String executeUrl(final String httpMethod, final String url, final String contentString,
        final String contentType) {

    HttpClient client = new HttpClient();

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(HTTP_REQUEST_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }

    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }

        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}