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

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

Introduction

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

Prototype

public UsernamePasswordCredentials(String paramString1, String paramString2) 

Source Link

Usage

From source file:com.sos.VirtualFileSystem.WebDAV.SOSVfsWebDAV.java

/**
 *
 * \brief doAuthenticate//  www.  j av  a 2s .c o  m
 *
 * \details
 *
 * \return ISOSConnection
 *
 * @param authenticationOptions
 * @return
 * @throws Exception
 */
private ISOSConnection doAuthenticate(final ISOSAuthenticationOptions pAuthenticationOptions) throws Exception {

    authenticationOptions = pAuthenticationOptions;

    userName = authenticationOptions.getUser().Value();
    password = authenticationOptions.getPassword().Value();

    logger.debug(SOSVfs_D_132.params(userName));

    HttpURL httpUrl = this.setRootHttpURL(userName, password, host, port);

    try {
        // eigentlich bereits bei new WebdavResource soll eine Exception ausgelst werden,
        // wenn die Credentials bzw host etc falsch sind
        // hier aber aus irgend. Grund kommt keine Exception hoch
        if (SOSString.isEmpty(proxyHost)) {
            davClient = new WebdavResource(httpUrl);
        } else {
            logger.info("using proxy: host " + proxyHost + ":" + proxyPort + " user = " + proxyUser);
            davClient = new WebdavResource(httpUrl, proxyHost, proxyPort,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }

        if (!davClient.exists()) {
            throw new JobSchedulerException("not connected " + davClient.getStatusMessage());
        }

    } catch (Exception ex) {
        throw new JobSchedulerException(SOSVfs_E_167.params(authenticationOptions.getAuth_method().Value(),
                authenticationOptions.getAuth_file().Value()), ex);
    }

    reply = "OK";
    logger.debug(SOSVfs_D_133.params(userName));
    this.LogReply();

    return this;
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* Extracts info from message context.//from w w  w.j av a 2 s  . c o  m
* 
* @param method
*            Post method
* @param httpClient
*            The client used for posting
* @param msgContext
*            the message context
* @param tmpURL
*            the url to post to.
* 
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
        * ISSUE: these are not the same, but MessageContext has only one
        * definition of timeout
        */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    //method.setRequestHeader(
    //   new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)")
    //);

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
        //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");
    }

    // add compression headers if needed
    // if we accept GZIP then add the accept-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        // accept both gzip and deflate if the gzip property is set
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
                HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE);
        //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE);
    }

    // if we will gzip the request then add the content-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION))
                continue;
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void publishPostGISTable(String name) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/crwgs84/datastores/public/featuretypes";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(new StringRequestEntity(
            "<?xml version=\"1.0\"?><featureType><name>" + name + "</name></featureType>"));
    post.setDoAuthentication(true);//  ww  w. j  a va  2s  .  co m

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }

}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Setup proxy access if we have to from settings.xml file configuration.
 * /*from ww  w  . j a  va  2s.com*/
 * @param client the HttpClient
 */
private void determineProxy(final HttpClient client) {
    // see whether there is any proxy defined in maven
    Proxy proxy = null;

    String proxyHost = null;

    int proxyPort = 0;

    String proxyUser = null;

    String proxyPass = null;

    if (this.project == null) {
        this.getLog().error("No project set. No proxy info available.");

        return;
    }

    if (this.settings != null) {
        proxy = this.settings.getActiveProxy();
    }

    if (proxy != null) {
        proxyHost = this.settings.getActiveProxy().getHost();

        proxyPort = this.settings.getActiveProxy().getPort();

        proxyUser = this.settings.getActiveProxy().getUsername();

        proxyPass = this.settings.getActiveProxy().getPassword();

        this.getLog().debug(proxyPass);
    }

    if (proxyHost != null) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        this.getLog().debug("Using proxy: " + proxyHost + " at port " + proxyPort);

        if (proxyUser != null) {
            this.getLog().debug("Using proxy user: " + proxyUser);

            client.getState().setProxyCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                    new UsernamePasswordCredentials(proxyUser, proxyPass));
        }
    }
}

From source file:com.xpn.xwiki.XWiki.java

public static HttpClient getHttpClient(int timeout, String userAgent) {
    HttpClient client = new HttpClient();

    if (timeout != 0) {
        client.getParams().setSoTimeout(timeout);
        client.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout));
    }//from  w w  w  .ja v a 2  s  .  c  o  m

    client.getParams().setParameter("http.useragent", userAgent);

    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if ((proxyHost != null) && (!proxyHost.equals(""))) {
        int port = 3128;
        if ((proxyPort != null) && (!proxyPort.equals(""))) {
            port = Integer.parseInt(proxyPort);
        }
        client.getHostConfiguration().setProxy(proxyHost, port);
    }

    String proxyUser = System.getProperty("http.proxyUser");
    if ((proxyUser != null) && (!proxyUser.equals(""))) {
        String proxyPassword = System.getProperty("http.proxyPassword");
        Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
    }

    return client;
}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

/**
 * /*from www .  j  a va2s.c  o m*/
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject searchAllTypeOfObjects(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order) throws Exception {
    logger.debug("----Inside searchAllTypeOfObjects query: " + query + " & select: " + select + " & order: "
            + order);
    GetMethod getMethod = null;
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/search.xml";

        logger.debug(
                "----Inside searchAllTypeOfObjects zenDeskURL: " + zenDeskURL + " & sessionId: " + sessionId);

        /* Instantiate get method */
        getMethod = new GetMethod(zenDeskURL);

        /* Set request content type */
        getMethod.addRequestHeader("Content-Type", "application/xml");

        /* Cookie is required to be set in case of search */
        getMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Check if user has not provided a valid query */
        if (ZDCRMMessageFormatUtils.validateQuery(query)) {
            getMethod.setQueryString(new NameValuePair[] {
                    new NameValuePair("query", ZDCRMMessageFormatUtils.createZDQuery(query)) });
        }

        /* Execute method */
        int result = httpclient.executeMethod(getMethod);
        logger.debug("----Inside searchAllTypeOfObjects response code: " + result + " & body: "
                + getMethod.getResponseBodyAsString());

        if (result == HttpStatus.SC_OK) {
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(getMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath.compile("/records/record");

            /* Get node list from resposne document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

            /* Get select field list */
            List<String> selectFieldList = null;

            /* Check if user is asking for all fields */
            if (select != null && !select.equalsIgnoreCase(HTTPConstants.allCRMObjectFields)) {
                selectFieldList = ZDCRMMessageFormatUtils.createSelectFieldList(select);
            }

            /* Iterate over node list */
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* Get node from node list */
                final Node node = nodeList.item(i);

                /* Create new Scribe object */
                final ScribeObject cADbject = new ScribeObject();

                /* Check if node has child nodes */
                if (node.hasChildNodes()) {

                    final NodeList subNodeList = node.getChildNodes();

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    for (int j = 0; j < subNodeList.getLength(); j++) {

                        /* Get all subnodes */
                        final Node subNode = subNodeList.item(j);

                        /* This trick is to avoid empty nodes */
                        if (!subNode.getNodeName().contains("#text")) {
                            if (selectFieldList != null) {
                                /* Add only user requested fields */
                                if (selectFieldList.contains(subNode.getNodeName().trim().toUpperCase())) {
                                    /* Create element from response */
                                    final Element element = ZDCRMMessageFormatUtils.createMessageElement(
                                            subNode.getNodeName(), subNode.getTextContent());

                                    /* Add element in list */
                                    elementList.add(element);
                                }
                            } else {
                                /* Create element from response */
                                final Element element = ZDCRMMessageFormatUtils
                                        .createMessageElement(subNode.getNodeName(), subNode.getTextContent());

                                /* Add element in list */
                                elementList.add(element);
                            }
                        }
                    }

                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }
            }
            /* Check if no record found */
            if (cADbjectList.size() == 0) {
                throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk");
            }

            /* Set the final object in command object */
            cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(getMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } catch (final Exception e) {
        throw new ScribeException(ScribeResponseCodes._1000 + "Problem while communicating with Zendesk CRM",
                e);
    } finally {
        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private void authenticate()
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {
    // WebClientUtil.setupHttpClient(httpClient, proxy, repositoryUrl, null,
    // null);/*from w ww .  j  av  a  2  s. c om*/
    if (!hasAuthenticationCredentials()) {
        throw new FogBugzClientException("No authentication credentials!");
    }

    // try standard basic/digest authentication first
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    httpClient.getState().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);

    GetMethod method = new GetMethod(WebClientUtil
            .getRequestPath(repositoryUrl + "/api.asp?cmd=logon&email=" + username + "&password=" + password));
    method.setFollowRedirects(false);
    int code;
    try {
        httpClient.getParams().setAuthenticationPreemptive(true);
        code = httpClient.executeMethod(method);
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new FogBugzClientException("Session might have expired!");
        }
        Response r = unmarshalResponse(method);
        authenticated = true;
        token = r.getToken();
    } finally {
        method.releaseConnection();
        httpClient.getParams().setAuthenticationPreemptive(false);
    }

    // the expected return code is a redirect, anything else is suspicious
    if (code == HttpURLConnection.HTTP_OK) {
        // try form-based authentication via AccountManagerPlugin as a
        // fall-back
        // authenticateAccountManager(httpClient);
    }

    // validateAuthenticationState(httpClient);

    // success since no exception was thrown

}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

private void setProxy(ProxyCfg prx) {
    HostConfiguration hostConfiguration = client.getHostConfiguration();
    if (prx != null) {
        ProxyHost proxyHost = new ProxyHost(prx.getHost(), prx.getPort());
        hostConfiguration.setProxyHost(proxyHost);
        if (prx.getUsername() != null) {
            UsernamePasswordCredentials upCred = new UsernamePasswordCredentials(prx.getUsername(),
                    prx.getPassword());/*ww  w  .ja v a 2s.  c  o  m*/
            client.getState().setProxyCredentials(AuthScope.ANY, upCred);
        } else {
            client.getState().clearProxyCredentials();
        }
    } else {
        hostConfiguration.setProxyHost(null);
        client.getState().clearProxyCredentials();
    }
}

From source file:net.sf.taverna.raven.plugins.PluginManager.java

public static void setProxy(HttpClient client) {
    String host = System.getProperty("http.proxyHost");
    String port = System.getProperty("http.proxyPort");
    String user = System.getProperty("http.proxyUser");
    String password = System.getProperty("http.proxyPassword");

    if (host != null && port != null) {
        try {/*from w  w w  .ja v a2s.c  o  m*/
            int portInteger = Integer.parseInt(port);
            client.getHostConfiguration().setProxy(host, portInteger);
            if (user != null && password != null) {
                client.getState().setProxyCredentials(new AuthScope(host, portInteger),
                        new UsernamePasswordCredentials(user, password));
            }
        } catch (NumberFormatException e) {
            logger.error("Proxy port not an integer", e);
        }
    }
}

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;/*from   w  w  w  . j  a  va 2  s.com*/
    HttpState httpState = null;

    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);
        }
    }
}