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

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

Introduction

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

Prototype

@Override
public Header[] getRequestHeaders() 

Source Link

Document

Returns an array of the requests headers that the HTTP method currently has

Usage

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Calculates the canonical and signed header strings in a single pass, done in one pass for efficiency
 * @param httpBaseRequest//from  w  w  w  . ja v  a2s .  c o  m
 * @return Array of 2 elements, first element is the canonicalHeader string, second element is the signedHeaders string
 */
private static String[] getCanonicalAndSignedHeaders(HttpMethodBase httpBaseRequest) {
    /*
     * The host header is required for EucaV2 signing, but it is not constructed by the HttpClient until the method is executed.
     * So, here we add a header with the same value and name so that we can do the proper sigining, but know that this value will
     * be overwritten when HttpMethodBase is executed to send the request.
     * 
     * This code is specific to the jakarta commons httpclient because that client will set the host header to hostname:port rather than
     * just hostname.
     * 
     * Supposedly you can force the value of the Host header with: httpBaseRequest.getParams().setVirtualHost("hostname"), but that was not successful
     */
    try {
        httpBaseRequest.addRequestHeader("Host",
                httpBaseRequest.getURI().getHost() + ":" + httpBaseRequest.getURI().getPort());
    } catch (URIException e) {
        LOG.error(
                "Could not add Host header for canonical headers during authorization header creation in HTTP client: ",
                e);
        return null;
    }

    Header[] headers = httpBaseRequest.getRequestHeaders();
    StringBuilder signedHeaders = new StringBuilder();
    StringBuilder canonicalHeaders = new StringBuilder();

    if (headers != null) {
        Arrays.sort(headers, new Comparator<Header>() {
            @Override
            public int compare(Header arg0, Header arg1) {
                return arg0.getName().toLowerCase().compareTo(arg1.getName().toLowerCase());
            }

        });

        for (Header header : headers) {
            //Add to the signed headers
            signedHeaders.append(header.getName().toLowerCase()).append(';');
            //Add the name and value to the canonical header
            canonicalHeaders.append(header.getName().toLowerCase()).append(':').append(header.getValue().trim())
                    .append('\n');
        }

        if (signedHeaders.length() > 0) {
            signedHeaders.deleteCharAt(signedHeaders.length() - 1); //Delete the trailing semi-colon
        }

        if (canonicalHeaders.length() > 0) {
            canonicalHeaders.deleteCharAt(canonicalHeaders.length() - 1); //Delete the trialing '\n' just to make things clear and consistent
        }
    }
    String[] result = new String[2];
    result[0] = canonicalHeaders.toString();
    result[1] = signedHeaders.toString();
    return result;
}

From source file:jeeves.utils.XmlRequest.java

private String getSentData(HttpMethodBase httpMethod) {
    StringBuilder sentData = new StringBuilder(httpMethod.getName()).append(" ").append(httpMethod.getPath());

    if (httpMethod.getQueryString() != null) {
        sentData.append("?" + httpMethod.getQueryString());
    }/* w w  w  .  ja  v  a  2s  .  c o  m*/

    sentData.append("\r\n");

    for (Header h : httpMethod.getRequestHeaders()) {
        sentData.append(h);
    }

    sentData.append("\r\n");

    if (httpMethod instanceof PostMethod) {
        sentData.append(postData);
    }

    return sentData.toString();
}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>/*from   w w w  .j  av a  2  s.c  o m*/
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Executes the HTTP request.// ww w .  ja v a 2  s  .  c  o m
 * @throws IOException if an Exception occurs
 */
public void execute() throws IOException {

    // initialize
    this.executionLog.setLength(0);
    StringBuffer log = this.executionLog;
    ResponseInfo respInfo = this.getResponseInfo();
    respInfo.reset();
    InputStream responseStream = null;
    HttpMethodBase method = null;

    try {
        log.append("HTTP Client Request\n").append(this.getUrl());

        // make the Apache HTTPClient
        HttpClient client = this.batchHttpClient;
        if (client == null) {
            client = new HttpClient();
            boolean alwaysClose = Val.chkBool(Val.chkStr(ApplicationContext.getInstance().getConfiguration()
                    .getCatalogConfiguration().getParameters().getValue("httpClient.alwaysClose")), false);
            if (alwaysClose) {
                client.setHttpConnectionManager(new SimpleHttpConnectionManager(true));
            }
        }

        // setting timeout info
        client.getHttpConnectionManager().getParams().setConnectionTimeout(getConnectionTimeOutMs());
        client.getHttpConnectionManager().getParams().setSoTimeout(getResponseTimeOutMs());

        // setting retries
        int retries = this.getRetries();

        // create the client and method, apply authentication and proxy settings
        method = this.createMethod();
        //method.setFollowRedirects(true);
        if (retries > -1) {
            // TODO: not taking effect yet?
            DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, true);
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        }

        this.applyAuthAndProxySettings(client, this.getUrl());

        // execute the method, determine basic information about the response
        respInfo.setResponseCode(client.executeMethod(method));
        this.determineResponseInfo(method);

        // collect logging info
        if (LOGGER.isLoggable(Level.FINER)) {
            log.append("\n>>").append(method.getStatusLine());
            log.append("\n--Request Header");
            for (Header hdr : method.getRequestHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }
            log.append("\n--Response Header");
            for (Header hdr : method.getResponseHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }

            //log.append(" responseCode=").append(this.getResponseInfo().getResponseCode());
            //log.append(" responseContentType=").append(this.getResponseInfo().getContentType());
            //log.append(" responseContentEncoding=").append(this.getResponseInfo().getContentEncoding());
            //log.append(" responseContentLength=").append(this.getResponseInfo().getContentLength());

            if (this.getContentProvider() != null) {
                String loggable = this.getContentProvider().getLoggableContent();
                if (loggable != null) {
                    log.append("\n--Request Content------------------------------------\n").append(loggable);
                }
            }
        }

        // throw an exception if an error is encountered
        if ((respInfo.getResponseCode() < 200) || (respInfo.getResponseCode() >= 300)) {
            String msg = "HTTP Request failed: " + method.getStatusLine();
            if (respInfo.getResponseCode() == HttpStatus.SC_UNAUTHORIZED) {
                AuthState authState = method.getHostAuthState();
                AuthScheme authScheme = authState.getAuthScheme();
                HttpClient401Exception authException = new HttpClient401Exception(msg);
                authException.setUrl(this.getUrl());
                authException.setRealm(authState.getRealm());
                authException.setScheme(authScheme.getSchemeName());
                if ((authException.getRealm() == null) || (authException.getRealm().length() == 0)) {
                    authException.setRealm(authException.generateHostBasedRealm());
                }
                throw authException;
            } else {
                throw new HttpClientException(respInfo.getResponseCode(), msg);
            }
        }

        // handle the response
        if (this.getContentHandler() != null) {
            if (getContentHandler().onBeforeReadResponse(this)) {
                responseStream = getResponseStream(method);
                if (responseStream != null) {
                    this.getContentHandler().readResponse(this, responseStream);
                }
            }

            // log thre response content
            String loggable = this.getContentHandler().getLoggableContent();
            long nBytesRead = this.getResponseInfo().getBytesRead();
            long nCharsRead = this.getResponseInfo().getCharactersRead();
            if ((nBytesRead >= 0) || (nCharsRead >= 0) || (loggable != null)) {
                log.append("\n--Response Content------------------------------------");
                if (nBytesRead >= 0)
                    log.append("\n(").append(nBytesRead).append(" bytes read)");
                if (nCharsRead >= 0)
                    log.append("\n(").append(nCharsRead).append(" characters read)");
                if (loggable != null)
                    log.append("\n").append(loggable);
            }
        }

    } finally {

        // cleanup
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to close HTTP response stream.", t);
        }
        try {
            if (method != null)
                method.releaseConnection();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to release HttpMethod", t);
        }

        // log the request/response
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(this.getExecutionLog().toString());
        }
    }
}

From source file:fedora.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    log.debug(this.getClass().getName() + ".connect() " + " url==" + urlString + " requestParameters=="
            + requestParameters + " requestCookies==" + requestCookies);
    responseCookies2 = null;/*  w w w. j  a va  2s. co  m*/
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        log.error(this.getClass().getName() + ".connect() " + "bad configured url==" + urlString);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        log.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        log.debug("DIAGNOSTIC urlString==" + urlString);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    /*
     * log.debug("\n-a-"); Protocol easyhttps = null; try { easyhttps = new
     * Protocol("https", (ProtocolSocketFactory) new
     * EasySSLProtocolSocketFactory(), 443); } catch (Throwable t) {
     * log.debug(t); log.debug(t.getMessage()); if (t.getCause() != null)
     * log.debug(t.getCause().getMessage()); } log.debug("\n-b-");
     * Protocol.registerProtocol("https", easyhttps); log.debug("\n-c-");
     */

    HttpClient client = new HttpClient();
    log.debug(this.getClass().getName() + ".connect() " + " b4 calling setup");
    log.debug(this.getClass().getName() + ".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    log.debug(this.getClass().getName() + ".connect() " + " after calling setup");
    int statusCode = 0;
    try {
        log.debug(this.getClass().getName() + ".connect() " + " b4 calling executeMethod");
        client.executeMethod(method);
        log.debug(this.getClass().getName() + ".connect() " + " after calling executeMethod");
        statusCode = method.getStatusCode();
        log.debug(
                this.getClass().getName() + ".connect() " + "(with configured url) statusCode==" + statusCode);
    } catch (Exception e) {
        log.error(this.getClass().getName() + ".connect() " + "failed original connect, url==" + urlString);
        log.error(e);
        log.error(e.getMessage());
        if (e.getCause() != null) {
            log.error(e.getCause().getMessage());
        }
        e.printStackTrace();
    }

    log.debug(this.getClass().getName() + ".connect() " + " status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    log.error(this.getClass().getName() + ".connect() " + "bad redirect, url==" + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    log.debug(this.getClass().getName() + ".connect() " + "(on redirect) statusCode=="
                            + statusCode);
                } catch (Exception e) {
                    log.error(this.getClass().getName() + ".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        log.debug(this.getClass().getName() + ".connect() " + "status code 200");
        String content = null;
        try {
            log.debug(this.getClass().getName() + ".connect() " + "b4 gRBAS()");
            content = method.getResponseBodyAsString();
            log.debug(this.getClass().getName() + ".connect() " + "after gRBAS() content==" + content);
        } catch (IOException e) {
            log.error(this.getClass().getName() + ".connect() " + "couldn't get content");
            return;
        }
        if (content == null) {
            log.error(this.getClass().getName() + ".connect() content==null");
            return;
        } else {
            log.debug(this.getClass().getName() + ".connect() content != null, about to new Tidy");
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                log.debug("new Tidy didn't");
                log.debug(t);
                log.debug(t.getMessage());
                if (t != null) {
                    log.debug(t.getCause().getMessage());
                }
            }
            log.debug(this.getClass().getName() + ".connect() after newing Tidy, tidy==" + tidy);
            byte[] inputBytes = content.getBytes();
            log.debug(this.getClass().getName() + ".connect() A1");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            log.debug(this.getClass().getName() + ".connect() A2");
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
            log.debug(this.getClass().getName() + ".connect() A3");
        }
        log.debug(this.getClass().getName() + ".connect() " + "b4 getState()");
        HttpState state = client.getState();
        log.debug(this.getClass().getName() + ".connect() state==" + state);
        try {
            responseCookies2 = method.getRequestHeaders();
            log.debug(this.getClass().getName() + ".connect() just got headers");
            for (Header element : responseCookies2) {
                log.debug(this.getClass().getName() + ".connect() header==" + element);
            }
            responseCookies = state.getCookies();
            log.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            log.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                log.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        log.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

private void setupSentData(HttpMethodBase httpMethod) {
    sentData = httpMethod.getName() + " " + httpMethod.getPath();

    if (httpMethod.getQueryString() != null)
        sentData += "?" + httpMethod.getQueryString();

    sentData += "\r\n";

    for (Header h : httpMethod.getRequestHeaders())
        sentData += h;//from   w ww  .  ja v a 2  s  .c om

    sentData += "\r\n";

    if (httpMethod instanceof PostMethod)
        sentData += postData;
}

From source file:org.fao.oaipmh.requests.Transport.java

private void setupSentData(HttpMethodBase httpMethod) {
    sentData = httpMethod.getName() + " " + httpMethod.getPath();

    if (httpMethod.getQueryString() != null)
        sentData += "?" + httpMethod.getQueryString();

    sentData += "\r\n";

    for (Header h : httpMethod.getRequestHeaders())
        sentData += h;//ww  w .j  a  v a2  s  .c  o m

    sentData += "\r\n";
}

From source file:org.fcrepo.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    if (logger.isDebugEnabled()) {
        logger.debug("Entered .connect() " + " url==" + urlString + " requestParameters==" + requestParameters
                + " requestCookies==" + requestCookies);
    }//from   w  w w  . j a v  a2s  .c om
    responseCookies2 = null;
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        logger.error("Malformed url: " + urlString, mue);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        logger.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        logger.debug("DIAGNOSTIC urlString==" + urlString);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    HttpClient client = new HttpClient();
    logger.debug(".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    int statusCode = 0;
    try {
        client.executeMethod(method);
        statusCode = method.getStatusCode();
    } catch (Exception e) {
        logger.error("failed original connect, url==" + urlString, e);
    }

    logger.debug("status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    logger.error(".connect() malformed redirect url: " + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    logger.debug(".connect() (on redirect) statusCode==" + statusCode);
                } catch (Exception e) {
                    logger.error(".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        String content = null;
        try {
            content = method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("Error getting content", e);
            return;
        }
        if (content == null) {
            logger.error("Content is null");
            return;
        } else {
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                logger.error("Error creating Tidy instance?!", t);
            }
            byte[] inputBytes = content.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
        }
        HttpState state = client.getState();
        try {
            responseCookies2 = method.getRequestHeaders();
            if (logger.isDebugEnabled()) {
                for (Header element : responseCookies2) {
                    logger.debug("Header: {}={}", element.getName(), element.getValue());
                }
            }
            responseCookies = state.getCookies();
            logger.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            logger.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                logger.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        logger.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:org.httpobjects.proxy.Proxy.java

protected Response proxyRequest(Request req, final HttpMethodBase method) {
    method.setFollowRedirects(false);//  w  w w  .  ja v  a 2s .c o  m

    String path = req.path().valueFor("path");
    if (!path.startsWith("/"))
        path = "/" + path;
    String query = getQuery(req);
    if (query == null) {
        query = "";
    } else {
        query = "?" + query;
    }
    String url = base + path + query;
    log.debug("doing a " + method.getClass().getSimpleName() + " for " + url);
    //      log.debug("Content type is " + req.representation().contentType());
    try {
        method.setURI(new URI(processUrl(url), true));
    } catch (URIException e1) {
        throw new RuntimeException("Error with uri: " + url, e1);
    }

    addRequestHeaders(req, method);

    if (req.representation().contentType() != null) {
        method.addRequestHeader("Content-Type", req.representation().contentType());
    }

    for (Header next : method.getRequestHeaders()) {
        log.debug("Sending header: " + next);
    }

    HttpClient client = createHttpClient();

    return executeMethod(client, method, req);

}