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

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

Introduction

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

Prototype

public void setProxy(String paramString, int paramInt)

Source Link

Usage

From source file:net.sf.dsig.verify.OCSPHelper.java

private HostConfiguration getHostConfiguration() {
    HostConfiguration config = new HostConfiguration();

    if (proxyHost != null && proxyPort != -1) {
        logger.debug("Setting proxy" + "; proxyHost=" + proxyHost + "; proxyPort=" + proxyPort);
        config.setProxy(proxyHost, proxyPort);
    }//w w w .java  2  s.  c o m

    return config;
}

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

private void applyProxySettings() {
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPortSt = System.getProperty("http.proxyPort");
    int proxyPort = 0;
    try {// w w w  .ja  v a 2s .  co  m
        if (proxyPortSt != null && proxyPortSt.length() > 0) {
            proxyPort = Integer.parseInt(proxyPortSt);
        }
    } catch (Exception e) {
        // nothing to do here
    }

    if (proxyHost != null && proxyHost.length() > 0) {
        HostConfiguration hostCfg = getHostConfiguration();
        hostCfg.setProxy(proxyHost, proxyPort);
        Log_OC.d(TAG, "Proxy settings: " + proxyHost + ":" + proxyPort);
    }
}

From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java

/**
 * Sends the request contained in the <code>ContentFactory</code>.
 * The <code>ContentFactory</code> will deliver the request as
 * an <code>InputStream</code>.
 *
 * @param request the ebics request/*from  w  w  w.j  a  va  2  s. c  om*/
 * @return the HTTP return code
* @throws AxelorException 
 */
public final int send(ContentFactory request) throws IOException, AxelorException {
    HttpClient httpClient;
    String proxyConfiguration;
    InputStream input;
    int retCode;

    httpClient = new HttpClient();
    EbicsBank bank = session.getUser().getEbicsPartner().getEbicsBank();
    DefaultHttpClient client = getSecuredHttpClient(EbicsCertificateService.getCertificate(bank, "ssl"));

    proxyConfiguration = AppSettings.get().get("http.proxy.host");

    if (proxyConfiguration != null && !proxyConfiguration.equals("")) {
        HostConfiguration hostConfig;
        String proxyHost;
        int proxyPort;

        hostConfig = httpClient.getHostConfiguration();
        proxyHost = AppSettings.get().get("http.proxy.host").trim();
        proxyPort = Integer.parseInt(AppSettings.get().get("http.proxy.port").trim());
        hostConfig.setProxy(proxyHost, proxyPort);
        if (!AppSettings.get().get("http.proxy.user").equals("")) {
            String user;
            String pwd;
            UsernamePasswordCredentials credentials;
            AuthScope authscope;

            user = AppSettings.get().get("http.proxy.user").trim();
            pwd = AppSettings.get().get("http.proxy.password").trim();
            credentials = new UsernamePasswordCredentials(user, pwd);
            authscope = new AuthScope(proxyHost, proxyPort);
            httpClient.getState().setProxyCredentials(authscope, credentials);
        }
    }

    input = request.getContent();
    retCode = -1;
    HttpPost post = new HttpPost(bank.getUrl());
    ContentType type = ContentType.TEXT_XML;
    HttpEntity entity = new InputStreamEntity(input, retCode, type);
    post.setEntity(entity);
    HttpResponse responseHttp = client.execute(post);
    retCode = responseHttp.getStatusLine().getStatusCode();
    response = new InputStreamContentFactory(responseHttp.getEntity().getContent());
    return retCode;
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

/**
 * Test the general integration of the WebProxy access through the running Jetty true:
 *///from w  w w  .ja  v a 2s . c  om
@Test
public void testJettyIntegration() throws Exception {
    TestURIResolver uriResolver = new TestURIResolver();
    proxy = new WebProxy(uriResolver);

    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
    } catch (IOException e) {
        fail("Port not in use after starting server");
    }

    // GET request
    HttpClient client = new HttpClient();
    HostConfiguration hc = new HostConfiguration();
    String hostName = SystemUtils.getLocalHostName();
    hc.setProxy(hostName, httpPort);
    client.setHostConfiguration(hc);
    GetMethod get = new GetMethod("http://foo.bar/");
    client.executeMethod(get);

    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();

    // POST request
    PostMethod post = new PostMethod("http://foo2.bar/");
    post.addParameter("a", "x");
    post.addParameter("a", "y");
    client.executeMethod(post);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount);
    assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"),
            uriResolver.lookupRequestArgument);
    assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size());
    assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a"));
    assertEquals("Posted parameter should be received.", 2,
            uriResolver.lookupRequestParameteres.get("a").length);
    assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]);
    assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]);
    assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString());
    post.releaseConnection();

    // Request with parameter and portno
    get = new GetMethod("http://foo2.bar:8090/?baz=boo");
    client.executeMethod(get);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount);
    assertEquals("URI resolver 2 lookup should be called with right URI.",
            new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument);
    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();
}

From source file:com.xerox.amazonws.common.AWSQueryConnection.java

private void configureHttpClient() {
    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams connParams = connMgr.getParams();
    connParams.setMaxTotalConnections(maxConnections);
    connParams.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, maxConnections);
    connMgr.setParams(connParams);//from w w  w  . j av a  2 s  .co  m
    hc = new HttpClient(connMgr);
    // NOTE: These didn't seem to help in my initial testing
    //         hc.getParams().setParameter("http.tcp.nodelay", true);
    //         hc.getParams().setParameter("http.connection.stalecheck", false); 
    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        hc.setHostConfiguration(hostConfig);
        log.info("Proxy Host set to " + proxyHost + ":" + proxyPort);
        if (proxyUser != null && !proxyUser.trim().equals("")) {
            if (proxyDomain != null) {
                hc.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUser, proxyPassword, proxyHost, proxyDomain));
            } else {
                hc.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
                        new UsernamePasswordCredentials(proxyUser, proxyPassword));
            }
        }
    }
}

From source file:de.fips.plugin.tinyaudioplayer.http.EclipseProxyConfiguration.java

@Override
public void setupProxyFor(final HostConfiguration hostConfig, final URI uri) {
    @Cleanup("close")
    val proxyTracker = new ServiceTracker(FrameworkUtil.getBundle(this.getClass()).getBundleContext(),
            IProxyService.class.getName(), null);
    proxyTracker.open();/*from w  w  w  . ja v a 2  s .c  o m*/
    val proxyService = (IProxyService) proxyTracker.getService();
    val proxyDataForHost = proxyService.select(uri);
    for (val data : proxyDataForHost) {
        if (data.getHost() == null)
            continue;
        hostConfig.setProxy(data.getHost(), data.getPort());
        break;
    }
}

From source file:com.apatar.http.HttpNode.java

@Override
protected void TransformTDBtoRDB(int mode) {
    DataBaseTools.completeTransfer();/*from w w  w.  jav  a 2 s.  c o  m*/
    HttpConnection conn = (HttpConnection) ApplicationData.getProject().getProjectData(getConnectionDataID())
            .getData();
    String url = conn.getUrl();
    HttpRequestMethod httpRequestMethod = (HttpRequestMethod) conn.getMethod();

    TableInfo ti = getTiForConnection(IN_CONN_POINT_NAME);

    TableInfo tiOut = getTiForConnection(OUT_CONN_POINT_NAME);

    List<Record> selectionList = DataBaseTools.intersectionRecords(tiOut.getRecords(), ti.getRecords(), true);

    // read values from result set and put it in request
    SQLQueryString sqs = DataBaseTools.CreateSelectString(ApplicationData.getTempDataBase().getDataBaseInfo(),
            new SQLCreationData(selectionList, ti.getTableName()), null);

    if (sqs == null) {
        return;
    }

    ResultSet rs;
    try {
        rs = DataBaseTools.executeSelect(sqs, ApplicationData.getTempJDBC());

        while (rs.next()) {
            KeyInsensitiveMap rsData = DataBaseTools.GetDataFromRS(rs);

            HttpMethod hm;

            if (httpRequestMethod == HttpRequestMethod.post) {
                hm = sendPost(url, rsData);
            } else {
                hm = sendGet(url, rsData);
            }

            HttpClient client = new HttpClient();
            if (ApplicationData.httpClient.isUseProxy()) {
                HostConfiguration hostConfig = client.getHostConfiguration();
                hostConfig.setProxy(ApplicationData.httpClient.getHost(), ApplicationData.httpClient.getPort());
                String proxyUser = ApplicationData.httpClient.getUserName();
                if (proxyUser != null) {
                    client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                            proxyUser, ApplicationData.httpClient.getPassword()));
                }
            }

            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            int status = client.executeMethod(hm);

            KeyInsensitiveMap datas = new KeyInsensitiveMap();

            if (status != HttpStatus.SC_OK) {
                datas.put("Response", "Upload failed, response=" + HttpStatus.getStatusText(status));
            } else {
                datas.put("Response", hm.getResponseBodyAsString());
            }

            ti = getTiForConnection(OUT_CONN_POINT_NAME);

            List<Record> recs = getTiForConnection(AbstractDataBaseNode.OUT_CONN_POINT_NAME).getSchemaTable()
                    .getRecords();

            for (int j = 1; j < recs.size(); j++) {
                Record rec = recs.get(j);
                datas.put(rec.getFieldName(), rs.getObject(rec.getFieldName()));
            }

            DataBaseTools.insertData(new DataProcessingInfo(ApplicationData.getTempDataBase().getDataBaseInfo(),
                    ti.getTableName(), ti.getRecords(), ApplicationData.getTempJDBC()), datas);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    DataBaseTools.completeTransfer();
}

From source file:greenfoot.export.mygame.MyGameClient.java

/**
 * Get a http client, configured to use the proxy if specified in Greenfoot config
 *//*from w  w w.j  a va  2 s  .co m*/
protected HttpClient getHttpClient() {
    HttpClient httpClient = new HttpClient();

    String proxyHost = Config.getPropString("proxy.host", null);
    String proxyPortStr = Config.getPropString("proxy.port", null);
    if (proxyHost != null && proxyHost.length() != 0 && proxyPortStr != null) {
        HostConfiguration hostConfig = httpClient.getHostConfiguration();

        int proxyPort = 80;
        try {
            proxyPort = Integer.parseInt(proxyPortStr);
        } catch (NumberFormatException nfe) {
        }

        hostConfig.setProxy(proxyHost, proxyPort);
        String proxyUser = Config.getPropString("proxy.user", null);
        String proxyPass = Config.getPropString("proxy.password", null);
        if (proxyUser != null) {
            AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            Credentials proxyCreds = new UsernamePasswordCredentials(proxyUser, proxyPass);
            httpClient.getState().setProxyCredentials(authScope, proxyCreds);
        }
    }

    return httpClient;
}

From source file:ch.cyberduck.core.http.HTTP3Session.java

protected HostConfiguration getHostConfiguration(Host host) {
    int port = host.getPort();
    final HostConfiguration configuration = new StickyHostConfiguration();
    if ("https".equals(host.getProtocol().getScheme())) {
        if (-1 == port) {
            port = 443;//from   w  ww.  j  ava  2 s.  c om
        }
        // Configuration with custom socket factory using the trust manager
        configuration.setHost(host.getHostname(), port,
                new org.apache.commons.httpclient.protocol.Protocol(host.getProtocol().getScheme(),
                        new SSLSocketFactory(this.getTrustManager(host.getHostname())), port));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if (proxy.isHTTPSProxyEnabled(host)) {
                configuration.setProxy(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host));
            }
        }
    } else if ("http".equals(host.getProtocol().getScheme())) {
        if (-1 == port) {
            port = 80;
        }
        configuration.setHost(host.getHostname(), port, new org.apache.commons.httpclient.protocol.Protocol(
                host.getProtocol().getScheme(), new DefaultProtocolSocketFactory(), port));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if (proxy.isHTTPProxyEnabled(host)) {
                configuration.setProxy(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host));
            }
        }
    }
    final HostParams parameters = configuration.getParams();
    parameters.setParameter(HttpMethodParams.USER_AGENT, this.getUserAgent());
    parameters.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    parameters.setParameter(HttpMethodParams.SO_TIMEOUT, this.timeout());
    parameters.setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "ISO-8859-1");
    parameters.setParameter(HttpClientParams.MAX_REDIRECTS, 10);
    return configuration;
}

From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java

private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle)
        throws IOException, EngineException {
    byte[] result = null;

    try {/*w  w  w.ja v  a  2  s.  c  o m*/
        Context context = infoShuttle.context;

        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        HostConfiguration hostConfiguration = connector.hostConfiguration;

        boolean trustAllServerCertificates = connector.isTrustAllServerCertificates();

        // Retrieving httpState
        getHttpState(connector, infoShuttle);

        Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array...");
        Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl);

        // Proxy configuration
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps());
        CertificateManager certificateManager = connector.certificateManager;

        URL url = null;
        String host = "";
        int port = -1;
        if (resourceUrl.toLowerCase().startsWith("https:")) {
            Engine.logEngine.debug("(HttpClient) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);

            Engine.logEngine
                    .debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            resourceUrl = url.getFile();
            Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl);
        } else {
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }

        Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl);
        Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser);
        Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite);
        if (infoShuttle.postFromUser && infoShuttle.postToSite) {
            method = new PostMethod(resourceUrl);
            ((PostMethod) method).setRequestEntity(
                    new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType,
                            infoShuttle.context.httpServletRequest.getCharacterEncoding()));
        } else {
            method = new GetMethod(resourceUrl);
        }

        HttpMethodParams httpMethodParams = method.getParams();

        // Cookie configuration
        if (handleCookie) {
            Engine.logEngine.debug("(HttpClient) Setting cookie policy.");
            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        String basicUser = connector.getAuthUser();
        String basicPassword = connector.getAuthPassword();
        String givenBasicUser = connector.getGivenAuthUser();
        String givenBasicPassword = connector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******");
        }

        // Setting HTTP headers
        Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:");
        String headerName, headerValue;
        for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) {
            headerName = (String) infoShuttle.userHeaderNames.get(k);
            // Cookies are handled by HttpClient, so we do not have to proxy Cookie header
            // See #986 (Multiples cookies don't work with some proxies)
            if (headerName.toLowerCase().equals("cookie")) {
                Engine.logEngine.debug("Cookie header ignored");
            } else {
                headerValue = (String) infoShuttle.userHeaderValues.get(k);
                method.setRequestHeader(headerName, headerValue);
                Engine.logEngine.debug(headerName + "=" + headerValue);
            }
        }

        // Getting the result
        executeMethod(method, connector, resourceUrl, infoShuttle);
        result = method.getResponseBody();

    } finally {
        if (method != null)
            method.releaseConnection();
    }

    return result;
}