Example usage for org.apache.commons.httpclient HostConfiguration setHost

List of usage examples for org.apache.commons.httpclient HostConfiguration setHost

Introduction

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

Prototype

public void setHost(String paramString, int paramInt)

Source Link

Usage

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Process a page.//from   w  w  w  .j  a v a 2  s  .c o  m
 */
public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        targetURL = new URI(target);
    } catch (URISyntaxException e) {
        IOException ioe = new IOException("Bad URI syntax: " + target);
        ioe.initCause(e);
        throw ioe;
    }
    setHostPrefix(targetURL);

    HttpClient httpClient = new HttpClient();
    HttpState httpState = new HttpState();
    HostConfiguration hostConfig = new HostConfiguration();
    HttpMethodBase httpMethod;

    // define host
    hostConfig.setHost(targetURL.getHost(), targetURL.getPort());

    // create http method
    String method = (String) request.getAttribute("cq.ext.app.method");
    if (method == null) {
        method = request.getMethod();
    }
    method = method.toUpperCase();
    boolean isPost = "POST".equals(method);
    String urlString = targetURL.getPath();
    StringBuffer query = new StringBuffer();
    if (targetURL.getQuery() != null) {
        query.append("?");
        query.append(targetURL.getQuery());
    }
    //------------ GET ---------------
    if ("GET".equals(method)) {
        // add internal props
        Iterator<String> iter = extraParams.keySet().iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String value = extraParams.get(name);
            if (query.length() == 0) {
                query.append("?");
            } else {
                query.append("&");
            }
            query.append(Text.escape(name));
            query.append("=");
            query.append(Text.escape(value));
        }
        if (passInput) {
            // add request params
            @SuppressWarnings("unchecked")
            Enumeration<String> e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                if (targetParamName.equals(name)) {
                    continue;
                }
                String[] values = request.getParameterValues(name);
                for (int i = 0; i < values.length; i++) {
                    if (query.length() == 0) {
                        query.append("?");
                    } else {
                        query.append("&");
                    }
                    query.append(Text.escape(name));
                    query.append("=");
                    query.append(Text.escape(values[i]));
                }
            }

        }
        httpMethod = new GetMethod(urlString + query);
        //------------ POST ---------------
    } else if ("POST".equals(method)) {
        PostMethod m = new PostMethod(urlString + query);
        httpMethod = m;
        String contentType = request.getContentType();
        boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
        if (mp) {
            //------------ MULTPART POST ---------------
            List<Part> parts = new LinkedList<Part>();
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                parts.add(new StringPart(name, value));
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        parts.add(new StringPart(name, values[i]));
                    }
                }
            }
            m.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams()));
        } else {
            //------------ NORMAL POST ---------------
            // add internal props
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                m.addParameter(name, value);
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        m.addParameter(name, values[i]);
                    }
                }
            }
        }
    } else {
        log.error("Unsupported method ''{0}''", method);
        throw new IOException("Unsupported http method " + method);
    }
    log.debug("created http connection for method {0} to {1}", method, urlString + query);

    // add some request headers
    httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent"));
    httpMethod.setFollowRedirects(!isPost);
    httpMethod.getParams().setSoTimeout(soTimeout);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // send request
    httpClient.executeMethod(hostConfig, httpMethod, httpState);
    String contentType = httpMethod.getResponseHeader("Content-Type").getValue();

    log.debug("External app responded: {0}", httpMethod.getStatusLine());
    log.debug("External app contenttype: {0}", contentType);

    // check response code
    int statusCode = httpMethod.getStatusCode();
    if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) {
        PrintWriter writer = response.getWriter();
        writer.println("External application returned status code: " + statusCode);
        return;
    } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
        String location = httpMethod.getResponseHeader("Location").getValue();
        if (location == null) {
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
            return;
        }
        response.sendRedirect(rewriteURL(location, false));
        return;
    }

    // open input stream
    InputStream in = httpMethod.getResponseBodyAsStream();

    // check content type
    if (contentType != null && contentType.startsWith("text/html")) {
        rewriteHtml(in, contentType, response);
    } else {
        // binary mode
        if (contentType != null) {
            response.setContentType(contentType);
        }
        OutputStream outs = response.getOutputStream();

        try {
            byte buf[] = new byte[8192];
            int len;

            while ((len = in.read(buf)) != -1) {
                outs.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:com.starit.diamond.client.processor.ServerAddressProcessor.java

/**
 * ?diamond??//from   www .  jav  a2s.c om
 * 
 * @param acquireCount
 *            ?01?
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.DEFAULT_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        } else {
            configServerAddress = Constants.DAILY_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    // ??serverURL by leiwen
    String serverAddressUrl = Constants.BASE_URI + "/" + clusterType;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address)) {
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("?");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.warn("??");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}

From source file:com.mengka.diamond.client.processor.ServerAddressProcessor.java

/**
 * ?diamond??/*from  w ww  .jav a  2s  . c om*/
 * 
 * @param acquireCount
 *            ?01?
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.CONFIG_DEFAULT_DOMAINNAME;
            port = Constants.CONFIG_DEFAULT_PORT;
        } else {
            configServerAddress = Constants.CONFIG_DAILY_DOMAINNAME;
            port = Constants.CONFIG_DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    String serverAddressUrl = Constants.SERVER_ADDRESS_URI;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address) && !address.startsWith("#")) {
                    if (address.contains(":")) {
                        address = address.substring(0, address.indexOf(":"));
                    }
                    if (address.contains("\\")) {
                        address = address.substring(0, address.indexOf("\\"));
                    }
                    if (address.contains("/")) {
                        address = address.substring(0, address.indexOf("/"));
                    }
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("?");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.error("??, hostsconfig.tbj.com");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;/*ww w . ja v a  2  s  .  c o  m*/
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
            diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 1,
    // boyan@taobao.com
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;/*from   w ww . jav a 2 s .  c  o m*/
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
            diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 1,
    // boyan@taobao.com
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:org.aksonov.mages.connection.ConnectionManager.java

/**
 * Gets the connection./*from   ww w  .  ja va 2s.  c  o  m*/
 * 
 * @param host the host
 * 
 * @return the connection
 */
private static HttpConnection getConnection(String host) {
    try {
        synchronized (hosts) {
            if (!hosts.contains(host)) {
                HttpURL httpURL = new HttpURL(host);
                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(httpURL.getHost(), httpURL.getPort());
                hosts.put(host, hostConfig);
            }
        }
        HostConfiguration hostConfig = hosts.get(host);
        //Log.d("ConnectionManager", "Retrieving connection from the pool");
        HttpConnection connection = connectionManager.getConnectionWithTimeout(hostConfig, TIMEOUT);

        return connection;
    } catch (Exception e) {
        Log.e("ConnectionManager.getConnection", e);
        return null;
    }
}

From source file:org.bbaw.pdr.ae.view.identifiers.internal.ConcurrenceSearchController.java

private String requestWebService(URL url) throws URISyntaxException, UnsupportedEncodingException {
    String result = null;//from   www  .  ja v  a 2s  .  c  o  m
    if (url != null) {
        HttpClient client = new HttpClient();

        // System.out.println("url " + url.toString());
        // PostMethod method = null;
        HttpClient httpclient = null;
        httpclient = new HttpClient();

        String urlString = new String(url.toString());
        if (urlString.contains(" ")) {
            // System.out.println("containts ws");
            urlString.replace(" ", "%20");
        }
        Pattern p = Pattern.compile("\\s");
        Matcher m = p.matcher(urlString);
        // while (m.find())
        // {
        // // System.out.println("\\s");
        // }
        urlString = m.replaceAll("%20");
        // while (m.find())
        // {
        // System.out.println("2.\\s");
        // }
        // urlString = URLEncoder.encode(urlString, "UTF-8");
        // urlString.replace("\\s+", "%20");
        GetMethod get = new GetMethod(urlString);
        HostConfiguration hf = new HostConfiguration();
        hf.setHost(urlString, url.getPort());
        httpclient.setHostConfiguration(hf);
        // get = new PostMethod(theURL);
        // LogHelper.logMessage("Before sending SMS Message: "+message);
        int respCode;
        try {
            respCode = httpclient.executeMethod(get);
            log = new Status(IStatus.INFO, Activator.PLUGIN_ID, "Response code: " + respCode);
            iLogger.log(log);
            // successful.

            /* send request */
            final int status = client.executeMethod(get);
            // LOG.debug("http status #execute: " +
            // Integer.toString(status));
            switch (status) {
            case HttpStatus.SC_NOT_IMPLEMENTED:
                get.releaseConnection();
                // throw new IOException("Solr Query #GET (" +
                // get.getURI().toString() + ") returned 501");
            default:
                result = get.getResponseBodyAsString();
                get.releaseConnection();
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.bonitasoft.connectors.webdav.exo.common.ExoConnector.java

/**
 * initiate client//w ww .j  a  va  2  s .  c o  m
 * 
 * @param host
 * @param port
 * @param username
 * @param password
 */
public void initClient(final String host, final int port, final String username, final String password) {

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("WebDAVConnector {host=" + host + ", port=" + port + ", username=" + username
                + ", password=******}");
    }

    final HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(host, port);

    final HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    final HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    final int maxHostConnections = 20;
    params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(params);

    client = new HttpClient(connectionManager);
    final Credentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(AuthScope.ANY, creds);
    client.setHostConfiguration(hostConfig);
}

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();/*from  w ww  .  j a v a  2 s.  c o  m*/
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}

From source file:org.exoplatform.bonitaextension.connectors.webdav.common.WebDAVClient.java

/**
 * Create a new webdav Client with a user name and a password to connect to eXo server
 *
 * @param host/*from   w w  w.  j  a va  2 s.com*/
 * @param port
 * @param username
 * @param password
 */
public WebDAVClient(String host, Long port, String username, String password) {

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("WebDAVConnector {host=" + host + ", port=" + port + ", username=" + username
                + ", password=******}");
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(host, port.intValue());

    HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    int maxHostConnections = 20;
    params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(params);

    client = new HttpClient(connectionManager);
    Credentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(AuthScope.ANY, creds);
    client.setHostConfiguration(hostConfig);

}