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:org.kopi.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//w w  w  .ja  va2 s  .  co m
 * @return the HTTP return code
 */
public final int send(ContentFactory request) throws IOException {
    HttpClient httpClient;
    String proxyConfiguration;
    PostMethod method;
    RequestEntity requestEntity;
    InputStream input;
    int retCode;

    httpClient = new HttpClient();
    proxyConfiguration = session.getConfiguration().getProperty("http.proxy.host");

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

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

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

    input = request.getContent();
    method = new PostMethod(session.getUser().getPartner().getBank().getURL().toString());
    method.getParams().setSoTimeout(30000);
    requestEntity = new InputStreamRequestEntity(input);
    method.setRequestEntity(requestEntity);
    method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    retCode = -1;
    retCode = httpClient.executeMethod(method);
    response = new InputStreamContentFactory(method.getResponseBodyAsStream());

    return retCode;
}

From source file:org.lockss.plugin.silverchair.PostHttpClientUrlConnection.java

/** Execute the request. */
public void execute() throws IOException {
    assertNotExecuted();//w w w .j  a v  a2 s  .c  o  m
    if (methodCode != LockssUrlConnection.METHOD_PROXY) {
        mimicSunRequestHeaders();
    }
    HostConfiguration hostConfig = client.getHostConfiguration();
    if (proxyHost != null) {
        hostConfig.setProxy(proxyHost, proxyPort);
    } else {
        hostConfig.setProxyHost(null);
    }
    if (localAddress != null) {
        hostConfig.setLocalAddress(localAddress.getInetAddr());
    } else {
        hostConfig.setLocalAddress(null);
    }
    if (sockFact != null) {
        SecureProtocolSocketFactory hcSockFact = sockFact.getHttpClientSecureProtocolSocketFactory();
        String host = url.getHost();
        int port = url.getPort();
        if (port <= 0) {
            port = UrlUtil.getDefaultPort(url.getProtocol().toLowerCase());
        }
        DISP_FACT.setFactory(host, port, hcSockFact);
        // XXX Would like to check after connection is made that cert check
        // was actually done, but there's no good way to get to the socket or
        // SSLContect, etc.
        isAuthenticatedServer = sockFact.requiresServerAuth();
    }
    isExecuted = true;
    responseCode = executeOnce(method);
}

From source file:org.lucterios.engine.transport.HttpTransportImpl.java

private HostConfiguration getHostCnx() {
    HostConfiguration host_cnx = new HostConfiguration();
    if (getUseProxy() && (!"".equals(mProxyServer)) && (mProxyPort != 0)) {
        String[] proxy_param = mProxyServer.split(":|@");
        if (proxy_param.length != 3)
            host_cnx.setProxy(mProxyServer, mProxyPort);
        else {// www  .j  a  v  a2  s . c o m
            host_cnx.setProxy(proxy_param[2], mProxyPort);
            Credentials credentials = new UsernamePasswordCredentials(proxy_param[0], proxy_param[1]);
            AuthScope authscope = new AuthScope(proxy_param[2], mProxyPort);
            m_Cnx.getState().setProxyCredentials(authscope, credentials);
        }
    }
    return host_cnx;
}

From source file:org.moxie.proxy.connection.ProxyDownload.java

/**
 * Do the download.//ww w  . j a va2  s  . c o m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (status == 1 && log.isLoggable(Level.FINE)) {
            Header[] header = get.getResponseHeaders();
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(get);
        }

        // Make sure the temporary file is created in
        // the destination folder, otherwise
        // dl.renameTo(dest) might not work
        // for example if you have a separate /tmp partition
        // on Linux
        File destinationFolder = dest.getParentFile();
        dest.getParentFile().mkdirs();
        File dl = File.createTempFile("moxie-", ".tmp", destinationFolder);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        copy(get.getResponseBodyAsStream(), out);
        out.close();

        // create folder structure after successful download
        // - no, we create it before the download!
        //dest.getParentFile().mkdirs();

        if (dest.exists()) {
            dest.delete();
        }
        dl.renameTo(dest);

        // preserve last-modified, if possible
        try {
            Header lastModified = get.getResponseHeader("Last-Modified");
            if (lastModified != null) {
                Date date = DateUtil.parseDate(lastModified.getValue());
                dest.setLastModified(date.getTime());
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "could not parse \"last-modified\" for " + url, e);
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:org.moxie.proxy.connection.ProxyHead.java

/**
 * Do the download (of the headers)./*from ww w.  j a  v a2 s .co m*/
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + url);

    MyHeadMethod head = new MyHeadMethod(url.toString());
    head.setFollowRedirects(true);
    try {
        int status = client.executeMethod(head);

        log.info("Download status: " + status);
        this.header = head.getResponseHeaders();
        this.statusLine = head.getStatusLine().toString();
        this.responseBody = head.getResponseBody();
        if (status == 1 && log.isLoggable(Level.FINE)) {
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(head.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(head.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(head);
        }

    } finally {
        head.releaseConnection();
    }
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

protected HostConfiguration getHostConfig(URI uri) throws Exception {
    Protocol protocol = Protocol.getProtocol(uri.getScheme().toLowerCase());

    String host = uri.getHost();/*from w  ww  .j  a  v a 2 s.  c o m*/
    int port = uri.getPort();
    HostConfiguration config = new HostConfiguration();
    config.setHost(host, port, protocol);
    if (StringUtils.isNotBlank(httpConnector.getProxyHostname())) {
        // add proxy support
        config.setProxy(httpConnector.getProxyHostname(), httpConnector.getProxyPort());
    }
    return config;
}

From source file:org.n52.oxf.util.IOHelper.java

protected static HostConfiguration getHostConfiguration(URL serviceURL) {
    HostConfiguration hostConfig = new HostConfiguration();

    // apply proxy settings:
    String host = System.getProperty("http.proxyHost");
    String port = System.getProperty("http.proxyPort");
    String nonProxyHosts = System.getProperty("http.nonProxyHosts");

    // check if service url is among the non-proxy-hosts:
    boolean serviceIsNonProxyHost = false;
    if (nonProxyHosts != null && nonProxyHosts.length() > 0) {
        String[] nonProxyHostsArray = nonProxyHosts.split("\\|");
        String serviceHost = serviceURL.getHost();

        for (String nonProxyHost : nonProxyHostsArray) {
            if (nonProxyHost.equals(serviceHost)) {
                serviceIsNonProxyHost = true;
                break;
            }/*w  w w. jav  a  2 s. co  m*/
        }
    }
    // set proxy:
    if (serviceIsNonProxyHost == false && host != null && host.length() > 0 && port != null
            && port.length() > 0) {
        int portNumber = Integer.parseInt(port);
        hostConfig.setProxy(host, portNumber);
        LOGGER.info("Using proxy: " + host + " on port: " + portNumber);
    }

    return hostConfig;
}

From source file:org.openmicroscopy.shoola.svc.transport.BasicChannel.java

/**
 * Creates a <code>HttpClient</code> to communicate.
 * @see HttpChannel#getCommunicationLink()
 *///from  w ww . j  a v a  2s.co  m
protected HttpClient getCommunicationLink() {
    HostConfiguration cfg = new HostConfiguration();
    cfg.setHost(serverURL);
    String proxyHost = System.getProperty(HttpChannel.PROXY_HOST);
    String proxyPort = System.getProperty(HttpChannel.PROXY_PORT);
    if (proxyHost != null && proxyPort != null) {
        int port = Integer.parseInt(proxyPort);
        cfg.setProxy(proxyHost, port);
    }

    HttpClient channel = new HttpClient();
    channel.setHostConfiguration(cfg);
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(connTimeout);
    channel.setParams(params);
    return channel;
}

From source file:org.opensaml.ws.soap.client.http.HttpClientBuilder.java

/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created.//from w  w w .j  a  v  a2 s . c  o  m
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}

From source file:org.pengyou.client.lib.DavSession.java

/**
 * Get a <code>HttpClient</code> instance.
 * This method returns a new client instance, when reset is true.
 *
 * @param reset The reset flag to represent whether the saved information
 *              is used or not./*from  w ww  . ja v a  2  s .  c om*/
 * @return An instance of <code>HttpClient</code>.
 * @exception IOException
 */
public HttpClient getSessionInstance(boolean reset) throws IOException {

    if (reset || client == null) {
        HttpURL httpURL = context.getHttpURL();
        client = new HttpClient();
        // Set a state which allows lock tracking
        client.setState(new WebdavState());
        HostConfiguration hostConfig = client.getHostConfiguration();
        hostConfig.setHost(httpURL);
        if (context.getProxyHost() != null && context.getProxyPort() > 0)
            hostConfig.setProxy(context.getProxyHost(), context.getProxyPort());

        if (hostCredentials == null) {
            String userName = httpURL.getUser();
            if (userName != null && userName.length() > 0) {
                hostCredentials = new UsernamePasswordCredentials(userName, httpURL.getPassword());
            }
        }

        if (hostCredentials != null) {
            HttpState clientState = client.getState();
            clientState.setCredentials(null, httpURL.getHost(), hostCredentials);
            clientState.setAuthenticationPreemptive(true);
        }

        if (proxyCredentials != null) {
            client.getState().setProxyCredentials(null, context.getProxyHost(), proxyCredentials);
        }
    }

    return client;
}