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

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

Introduction

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

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectInstanceUserReport getLearningObjectInstanceUserReport(int instanceId,
        int learningObjectId, int userId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports/%s",
            learningObjectId, instanceId, userId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    LearningObjectInstanceUserReport report = new LearningObjectInstanceUserReport();
    try {/*from   w  ww. j  av  a  2  s  .  co m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                report = deserializeXMLToLearningObjectInstanceUserReport(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return report;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<OrganisationRole> getOrganisationRolesForCurrentUser() throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/OrganizationRolesForCurrentUser");
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<OrganisationRole> organizationRolesForUser = new ArrayList<OrganisationRole>();
    try {//from ww w.j  a  va  2s.c  om
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationRolesForUser = deserializeXMLToOrganisationRoles(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationRolesForUser;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<Organisation> getOrganisationsForLearningObjectInstance(int learningObjectId, int instanceId)
        throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Organizations",
            learningObjectId, instanceId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<Organisation> organizationsForLearningToolCreator = new ArrayList<Organisation>();
    try {//from w w  w  . j  a va 2s .  com
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationsForLearningToolCreator = deserializeXMLToOrganisations(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationsForLearningToolCreator;
}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

/**
 * Perform the HTTP request.  Can only be performed once.
 *///from w  w w . j  a  v  a  2s . c  o m
public void makeRequest() throws IOException, HttpClientException {
    if (requestMade) {
        return;
    }

    requestMade = true;
    RequestEntity reqEntity = null;
    NameValuePair[] postBody = null;
    if (isPostMethod()) {
        setMethodType("POST");
    }
    HttpMethod method = initMethod();
    if (isPostMethod()) {
        reqEntity = getRequestEntity((PostMethod) method);
        if (null != reqEntity) {
            logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

            ((PostMethod) method).setRequestEntity(reqEntity);
        } else {
            logger.debug("preparing to post form data");
            postBody = getRequestBody((PostMethod) method);
            ((PostMethod) method).setRequestBody(postBody);
        }
    }
    logger.debug("calling preMakeRequest");
    if (!preMakeRequest(method)) {
        return;
    }
    logger.debug("calling doAuthentication...");
    if (!doAuthentication(method)) {
        return;
    }
    int bytesread = 0;
    try {
        if (!isPostMethod()) {
            method.setFollowRedirects(true);
        }
        logger.debug("make request...");
        resultCode = httpc.executeMethod(method);
        reasonCode = method.getStatusText();
        if (isPostMethod()) {
            //check redirect after post
            method = checkFollowRedirect(method, resultCode);
        }
        logger.debug("check needs reauth...");

        if (needsReAuthentication(resultCode, method)) {
            logger.debug("re-authentication needed, performing...");
            method.releaseConnection();
            method.abort();
            //need to re-authenticate.
            method = initMethod();
            if (isPostMethod() && null != reqEntity) {
                ((PostMethod) method).setRequestEntity(reqEntity);
            } else if (isPostMethod() && null != postBody) {
                ((PostMethod) method).setRequestBody(postBody);
            }
            if (!doAuthentication(method)) {
                //user login failed
                return;
            }
            //user login has succeeded
            logger.debug("remaking original request...");
            resultCode = httpc.executeMethod(method);
            reasonCode = method.getStatusText();
            if (needsReAuthentication(resultCode, method)) {
                //user request was unauthorized
                throw new HttpClientException("Unauthorized Action: "
                        + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                        .getValue()
                                : reasonCode));
            }
        }

        logger.debug("finish...");
        if (null != method.getResponseHeader("Content-Type")) {
            resultType = method.getResponseHeader("Content-Type").getValue();
        }
        String type = resultType;
        if (type != null && type.indexOf(";") > 0) {
            type = type.substring(0, type.indexOf(";")).trim();
        }
        if (null == expectedContentType || expectedContentType.equals(type)) {
            if (null != destinationStream && resultCode >= 200 && resultCode < 300) {
                //read the input stream and write it to the destination
                contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(),
                        destinationStream);
            } else {
                final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50);
                Streams.copyStream(method.getResponseBodyAsStream(), outputBytes);
                resultStream = new ByteArrayInputStream(outputBytes.toByteArray());
            }
        }
        reqMadeMethod = method;
    } catch (HttpException e) {
        logger.error("HTTP error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    logger.debug("Response received");
    postMakeRequest();
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectiveReportSettings getLearningObjectiveReportSettings(int learningObjectId, int instanceId,
        int assessUserId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveReportSettings",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("assessUserId", Integer.toString(assessUserId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    LearningObjectiveReportSettings loReportSettings = new LearningObjectiveReportSettings();
    try {/*w w w  .ja  va 2  s .  c  o m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loReportSettings = deserializeXMLToLearningObjectiveReportSettings(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loReportSettings;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<LearningObjectiveAssessment> getLearningObjectiveUserAssessments(int learningObjectId,
        int instanceId, int userId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveUserAssessments",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("userId", Integer.toString(userId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    List<LearningObjectiveAssessment> loAssessments = new ArrayList<LearningObjectiveAssessment>();
    try {//from   w w w.  java  2  s. c o m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loAssessments = deserializeXMLToListOfLearningObjectiveAssessment(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loAssessments;
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Check endpoint url.//from   w  ww .  j ava 2  s  .c o  m
 *
 * @param endPointUrl endpoint url
 * @throws IOException on error
 */
protected void checkEndPointUrl(String endPointUrl) throws IOException {
    HttpMethod getMethod = new GetMethod(endPointUrl);
    getMethod.setFollowRedirects(false);
    try {
        int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, getMethod);
        if (status == HttpStatus.SC_UNAUTHORIZED) {
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        } else if (status != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw DavGatewayHttpClientFacade.buildHttpException(getMethod);
        }
        // check Location
        Header locationHeader = getMethod.getResponseHeader("Location");
        if (locationHeader == null || !"/ews/services.wsdl".equalsIgnoreCase(locationHeader.getValue())) {
            throw new IOException("Ews endpoint not available at " + getMethod.getURI().toString());
        }
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer)
 *///from w  ww  .jav a  2s.co  m
@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {
    logger.debug("BEGIN perform(GVBuffer gvBuffer)");
    HttpMethod method = null;
    try {
        String currMethodURI = null;
        Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true);

        String currHost = PropertiesHandler.expand(host, params, gvBuffer);
        String currPort = PropertiesHandler.expand(port, params, gvBuffer);
        logger.debug("Server Host: " + currHost + " - Port: " + currPort);
        httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol);

        auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params);
        proxy.setProxy(httpClient, gvBuffer, params);

        currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer);
        logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]");
        switch (methodName) {
        case OPTIONS:
            method = new OptionsMethod();
            break;
        case GET:
            method = new GetMethod();
            break;
        case HEAD:
            method = new HeadMethod();
            break;
        case POST:
            method = new PostMethod();
            break;
        case PUT:
            method = new PutMethod();
            break;
        case DELETE:
            method = new DeleteMethod();
            break;
        default:
            throw new CallException("GV_CALL_SERVICE_ERROR",
                    new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                            { "id", gvBuffer.getId().toString() },
                            { "message", "Unknown method = " + methodName } });
        }
        method.setURI(new URI(currMethodURI, uriEscaped));

        if ((refDP != null) && (refDP.length() > 0)) {
            logger.debug("Calling configured Data Provider: " + refDP);
            DataProviderManager dataProviderManager = DataProviderManager.instance();
            IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP);
            try {
                dataProvider.setContext(method);
                dataProvider.setObject(gvBuffer);
                method = (HttpMethod) dataProvider.getResult();
            } finally {
                dataProviderManager.releaseDataProvider(refDP, dataProvider);
            }
        }

        int status = httpClient.executeMethod(method);
        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status));
        String statusTxt = method.getStatusText();
        gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL"));
        Header[] responseHeaders = method.getResponseHeaders();
        for (Header header : responseHeaders) {
            String headerName = RESPONSE_HEADER_PREFIX + header.getName();
            String value = header.getValue();
            if (value == null) {
                value = "";
            }
            gvBuffer.setProperty(headerName, value);
        }
        String cType = "text/html";
        Header cTypeHeader = method.getResponseHeader("Content-Type");
        if (cTypeHeader != null) {
            String cTypeValue = cTypeHeader.getValue();
            if (cTypeValue != null) {
                cType = cTypeValue;
            }
        }
        logger.debug("Response content-type: " + cType);
        ContentType contentType = new ContentType(cType);
        byte[] responseBody = method.getResponseBody();
        Object object = responseBody;
        if (contentType.getPrimaryType().equals("multipart")) {
            object = handleMultipart(responseBody, cType);
        }
        gvBuffer.setObject(object);
    } catch (CallException exc) {
        throw exc;
    } catch (Exception exc) {
        logger.error("ERROR perform(GVBuffer gvBuffer)", exc);
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END perform(GVBuffer gvBuffer)");
    }
    return gvBuffer;
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();/*from   w  ww .j  av  a2s.  c  o  m*/
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;
    HttpState httpState = null;//www.ja  v  a  2  s. c  o m

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) | ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if ((cookies != null) && (cookies.length > 0)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            Header contentLength = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLength != null) {
                response.setContentLength(GetterUtil.getInteger(contentLength.getValue()));
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            bytes = FileUtil.getBytes(inputStream);
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}