Example usage for org.apache.commons.httpclient HttpClient getHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient getHostConfiguration

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:com.predic8.membrane.integration.ProxySSLConnectionMethodTest.java

@Test
public void testSSLConnectionMethod() throws Exception {
    HttpClient client = new HttpClient();
    client.getHostConfiguration().setProxy("localhost", 3129);

    GetMethod post = new GetMethod("https://www.google.com/");
    client.executeMethod(post);//from   ww w.jav  a2s  .co m
    AssertUtils.assertContains("<html", post.getResponseBodyAsString());

    client.getHttpConnectionManager().closeIdleConnections(0);
}

From source file:com.motorola.studio.android.localization.translators.GoogleTranslator.java

/**
 * Creates an HTTP request with the URL, execute it as a get, and returns
 * the a string with the result.//w ww.  j a  v a  2  s.  c  om
 * 
 * @param url
 *            URL to be executed.
 * @return String with the URL execution result.
 * @throws IOException
 *             If an exception occurs on transport
 * @throws HttpException
 *             If an exception occurs on the protocol
 * @throws Exception
 *             on error.
 */
protected static String executeHttpGetRequest(final URL url) throws HttpException {

    // Checking query size due to google policies
    if (url.toString().length() > MAX_QUERY_SIZE) {
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);
    }

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new ProxyAuthenticator());
        String urlStr = url.toString();
        if (urlStr.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using https proxy"); //$NON-NLS-1$
        } else if (urlStr.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.debug(GoogleTranslator.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if (proxyData.getUserId() != null && proxyData.getUserId().trim().length() > 0) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    // Creating the method to be executed, the URL at this point is enough
    // because it is complete
    GetMethod method = new GetMethod(url.toString());

    // Set method to be retried three times in case of error
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(RETRIES, false));

    method.setRequestHeader(REFERER_HEADER, REFERER_SITE);

    // Set the connection timeout               
    client.getHttpConnectionManager().getParams().setConnectionTimeout(new Integer(TIMEOUT));

    String result = ""; //$NON-NLS-1$
    try {
        // Execute the method.
        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            result = method.getResponseBodyAsString(MAX_SIZE);
        } catch (IOException e) {
            throw new HttpException(TranslateNLS.GoogleTranslator_Error_CannotConnectToServer + e.getMessage());
        }

        checkStatusCode(statusCode, result);

        // Unescape any possible unicode char
        result = unescapeUnicode(result);

        // Unescape any possible HTML sequence
        result = unescapeHTML(result);

    }

    finally {
        // Release the connection.
        method.releaseConnection();
    }

    return result;
}

From source file:com.collabnet.svnedge.net.CommonsHTTPProxySender.java

@Override
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL url) {
    client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    if (this.proxyUser != null) {
        client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));
    }/*  ww  w .  j a  va  2  s.  co m*/

    setupHttpClient(client, url.toString());
    // This needs to be set to 1.0 otherwise errors
    client.getHostConfiguration().getParams().setParameter(HttpClientParams.PROTOCOL_VERSION,
            HttpVersion.HTTP_1_0);
    httpClient = client;
    return client.getHostConfiguration();
}

From source file:ch.cyberduck.core.davs.DAVSSession.java

@Override
protected void configure() throws IOException {
    super.configure();
    final HttpClient client = this.getClient().getSessionInstance(this.getClient().getHttpURL(), false);
    client.getHostConfiguration().setHost(host.getHostname(), host.getPort(),
            new org.apache.commons.httpclient.protocol.Protocol("https",
                    (ProtocolSocketFactory) new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()),
                    host.getPort()));//from  ww  w  .  j  a v a2  s . c o  m
    //        final Proxy proxy = ProxyFactory.instance();
    //        if(proxy.isHTTPSProxyEnabled()) {
    //            this.getClient().setProxy(proxy.getHTTPSProxyHost(), proxy.getHTTPSProxyPort());
    //            //this.DAV.setProxyCredentials(new UsernamePasswordCredentials(null, null));
    //        }
    //        else {
    //            this.getClient().setProxy(null, -1);
    //            //this.DAV.setProxyCredentials(null);
    //        }
}

From source file:be.fedict.trust.crl.OnlineCrlRepository.java

private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException,
        NoSuchProviderException, NoSuchParserException, StreamParsingException {
    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }//from   www  .j a v  a  2  s. co m
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }
    String downloadUrl = crlUri.toURL().toString();
    LOG.debug("downloading CRL from: " + downloadUrl);
    GetMethod getMethod = new GetMethod(downloadUrl);
    getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
    int statusCode = httpClient.executeMethod(getMethod);
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        return null;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream());
    LOG.debug("CRL size: " + crl.getEncoded().length + " bytes");
    return crl;
}

From source file:com.zimbra.cs.httpclient.HttpProxyUtil.java

public static synchronized void configureProxy(HttpClient client) {
    try {/*from ww  w  .  j ava2 s.  com*/
        String url = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraHttpProxyURL,
                null);
        if (url == null)
            return;

        // need to initializae all the statics
        if (sProxyUrl == null || !sProxyUrl.equals(url)) {
            sProxyUrl = url;
            sProxyUri = new URI(url);
            sProxyAuthScope = null;
            sProxyCreds = null;
            String userInfo = sProxyUri.getUserInfo();
            if (userInfo != null) {
                int i = userInfo.indexOf(':');
                if (i != -1) {
                    sProxyAuthScope = new AuthScope(sProxyUri.getHost(), sProxyUri.getPort(), null);
                    sProxyCreds = new UsernamePasswordCredentials(userInfo.substring(0, i),
                            userInfo.substring(i + 1));
                }
            }
        }
        if (ZimbraLog.misc.isDebugEnabled()) {
            ZimbraLog.misc.debug("setting proxy: " + url);
        }
        client.getHostConfiguration().setProxy(sProxyUri.getHost(), sProxyUri.getPort());
        if (sProxyAuthScope != null && sProxyCreds != null)
            client.getState().setProxyCredentials(sProxyAuthScope, sProxyCreds);
    } catch (ServiceException e) {
        ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e);
    }
}

From source file:com.tasktop.c2c.server.common.service.HttpProxySetup.java

/**
 * Configure an http client to use the http proxy if it is set.
 * //from  w ww  . j av a 2 s . c  o m
 * @param httpClient
 */
public void configureHttpClient(HttpClient httpClient) {
    if (httpProxyHost != null && !httpProxyHost.isEmpty()) {
        httpClient.getHostConfiguration().setProxy(httpProxyHost, httpProxyPort);
    }
}

From source file:com.apatar.core.ApatarHttpClient.java

private String sendHttpQuery(HttpMethod method) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    HostConfiguration hostConfig = client.getHostConfiguration();
    if (isUseProxy) {
        hostConfig.setProxy(host, port);

        if (userName != null && !userName.equals("")) {
            client.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(userName, password, "", ""));
        }//from  w w w .  j  a  v a2s . c  om
    }

    client.executeMethod(method);

    return method.getResponseBodyAsString();
}

From source file:it.greenvulcano.gvesb.http.auth.impl.DummyHttpAuth.java

@Override
public void setProxyAuthentication(HttpClient client, String host, int port, GVBuffer gvBuffer,
        Map<String, Object> props) throws HttpAuthException {
    try {/*from w  ww  .  j  a v  a  2 s  .c o m*/
        client.getHostConfiguration().setProxy(host, port);
    } catch (Exception exc) {
        throw new HttpAuthException("Error using Dummy proxy authenticator", exc);
    }
}

From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java

/**
 * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[],
 *      String, String)//from  ww  w.  ja  v  a 2s.c  om
 */
public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset)
        throws IOTransferException {
    if (_sRequestCharset == null) {
        _sRequestCharset = "utf-8";
    }

    //1. to create http client and set proxy
    HttpClient client = new HttpClient();
    if (m_proxyHost != null) {
        client.getHostConfiguration().setProxyHost(m_proxyHost);
        if (m_sProxyUser != null & m_sProxyPassword != null) {
            client.getState().setProxyCredentials(//
                    new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()),
                    new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword));
        }
    }

    //2. to create post
    PostMethod method = new PostMethod(_sUrl);
    if (m_nRetryCount > 0) {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, //
                new DefaultHttpMethodRetryHandler(m_nRetryCount, false));
    }
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset);
    for (int i = 0; _args != null && i < _args.length; i++) {
        method.addParameter(_args[i]);
    }

    //3. to send request and read response
    String sResponse;
    try {
        client.executeMethod(method);
        sResponse = method.getResponseBodyAsString();
        if (!method.getRequestCharSet().equals(_sRequestCharset)) {
            sResponse = new String(sResponse.getBytes(), _sResponseCharset);
        }
        return sResponse;
    } catch (Exception ex) {
        throw new IOTransferException(_sUrl, ex);
    } finally {
        method.releaseConnection();
    }
}