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

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

Introduction

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

Prototype

public HttpClientParams getParams() 

Source Link

Usage

From source file:org.candlepin.client.DefaultCandlepinClientFacade.java

protected CandlepinConsumerClient clientWithCredentials(String username, String password) {
    try {/* w  ww .ja  v a2 s.  c  o m*/
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setAuthenticationPreemptive(true);
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        httpclient.getState().setCredentials(AuthScope.ANY, creds);
        CustomSSLProtocolSocketFactory factory = new CustomSSLProtocolSocketFactory(config, false);
        setHttpsProtocol(httpclient, factory);
        CandlepinConsumerClient client = ProxyFactory.create(CandlepinConsumerClient.class,
                config.getServerURL(), new ApacheHttpClientExecutor(httpclient));
        return client;
    } catch (Exception e) {
        throw new ClientException(e);
    }
}

From source file:org.carrot2.util.httpclient.HttpUtils.java

/**
 * Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses
 * compressed response streams, if supported by the server.
 * /*from   w  w  w  .ja va2 s . c  om*/
 * @param url The URL to open. The URL must be properly escaped, this method will
 *            <b>not</b> perform any escaping.
 * @param params Query string parameters to be attached to the url.
 * @param headers Any extra HTTP headers to add to the request.
 * @param user if not <code>null</code>, the user name to send during Basic
 *            Authentication
 * @param password if not <code>null</code>, the password name to send during Basic
 *            Authentication
 * @return The {@link HttpUtils.Response} object. Note that entire payload is read and
 *         buffered so that the HTTP connection can be closed when leaving this
 *         method.
 */
public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers,
        String user, String password, int timeout) throws HttpException, IOException {
    final HttpClient client = HttpClientFactory.getTimeoutingClient(timeout);
    client.getParams().setVersion(HttpVersion.HTTP_1_1);

    final GetMethod request = new GetMethod();

    if (user != null && password != null) {
        client.getState().setCredentials(new AuthScope(null, 80, null),
                new UsernamePasswordCredentials(user, password));
        request.setDoAuthentication(true);
    }

    final Response response = new Response();
    try {
        request.setURI(new URI(url, true));

        if (params != null) {
            request.setQueryString(params.toArray(new NameValuePair[params.size()]));
        }

        request.setRequestHeader(HttpHeaders.URL_ENCODED);
        request.setRequestHeader(HttpHeaders.GZIP_ENCODING);
        if (headers != null) {
            for (Header header : headers)
                request.setRequestHeader(header);
        }

        org.slf4j.LoggerFactory.getLogger(HttpUtils.class).debug("GET: " + request.getURI());

        final int statusCode = client.executeMethod(request);
        response.status = statusCode;

        InputStream stream = request.getResponseBodyAsStream();
        final Header encoded = request.getResponseHeader("Content-Encoding");
        if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) {
            stream = new GZIPInputStream(stream);
            response.compression = COMPRESSION_GZIP;
        } else {
            response.compression = COMPRESSION_NONE;
        }

        final Header[] respHeaders = request.getResponseHeaders();
        response.headers = new String[respHeaders.length][];
        for (int i = 0; i < respHeaders.length; i++) {
            response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() };
        }

        response.payload = StreamUtils.readFullyAndClose(stream);
        return response;
    } finally {
        request.releaseConnection();
    }
}

From source file:org.cbarrett.lcbo.LCBOClient.java

public LCBOClient(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;

    CommonsClientHttpRequestFactory factory = (CommonsClientHttpRequestFactory) restTemplate
            .getRequestFactory();/* w  w  w . j a v  a 2  s .  c  om*/
    HttpClient client = factory.getHttpClient();

    client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.useragent", "lcbo-tools");
}

From source file:org.codeartisans.proxilet.Proxilet.java

private HttpClient createClientWithLogin() {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    Protocol.registerProtocol("https", SSL_PROTOCOL);

    // if login/password authentication is required :
    if (targetCredentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        String[] creds = targetCredentials.split(":");
        Credentials defaultcreds = new UsernamePasswordCredentials(creds[0], creds[1]);
        httpClient.getState().setCredentials(new AuthScope(targetHost, targetPort, AuthScope.ANY_REALM),
                defaultcreds);/*w ww .ja v  a  2s .c om*/
    }
    return httpClient;
}

From source file:org.codehaus.mojo.fitnesse.FitnesseRemoteRunnerMojo.java

void getRemoteResource(String pUrl, OutputStream pOutStream, Fitnesse pServer) throws MojoExecutionException {
    try {/*from   w  w w  .  j ava  2  s  .  c  o  m*/
        HttpClient tClient = new HttpClient();
        getLog().info("Request resources from [" + pUrl + "]");
        if (pServer.getServerId() != null) {
            tClient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = getCredential(pServer.getServerId());
            AuthScope tAuthScope = new AuthScope(pServer.getHostName(), pServer.getPort(), AuthScope.ANY_REALM);
            tClient.getState().setCredentials(tAuthScope, defaultcreds);
            getLog().info("Use credential for remote connection");
        }
        HttpMethod tMethod = new GetMethod(pUrl);
        int tStatusCode = tClient.executeMethod(tMethod);
        if (tStatusCode != 200) {
            throw new MojoExecutionException(
                    "Bad response code from resource [" + pUrl + "], return code=[" + tStatusCode + "]");
        }

        InputStream tResponseStream = tMethod.getResponseBodyAsStream();
        byte[] tbytes = new byte[512];
        int tReadBytes = tResponseStream.read(tbytes);
        while (tReadBytes >= 0) {
            pOutStream.write(tbytes, 0, tReadBytes);
            tReadBytes = tResponseStream.read(tbytes);
        }
        pOutStream.flush();
        tMethod.releaseConnection();
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to read FitNesse server response.", e);
    } finally {
        try {
            pOutStream.close();
        } catch (IOException e) {
            getLog().error("Unable to close Stream.");
        }
    }
}

From source file:org.codehaus.swizzle.confluence.ConfluenceExportDecorator.java

/**
 * //  w  w w .jav  a 2 s .  co m
 * @param space
 * @param pageTitle
 * @param format
 * @param outputFile
 * @throws Exception 
 */
public final void exportPage(String space, String pageTitle, ExportFormat format, final java.io.File outputFile)
        throws Exception {
    assert space != null;
    assert pageTitle != null;
    assert format != null;
    assert outputFile != null;

    if (space == null) {
        throw new IllegalArgumentException("space is null!");
    }
    if (pageTitle == null) {
        throw new IllegalArgumentException("pageTitle is null!");
    }
    if (format == null) {
        throw new IllegalArgumentException("format is null!");
    }
    if (outputFile == null) {
        throw new IllegalArgumentException("outputFile is null!");
    }
    if (outputFile.exists() && !outputFile.isFile()) {
        throw new IllegalArgumentException("outputFile is not a file!");
    }

    final Page page = confluence.getPage(space, pageTitle);

    final HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    login(client, String.format("%s?pageId=%s", format.url, page.getId()), new RedirectTask() {

        @Override
        public void exec(String location) throws Exception {
            exportpdf(client, location, outputFile);
        }
    });

}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java

public HttpClient makeClient(CSPRequestCredentials creds, CSPRequestCache cache) {
    // Check request cache
    HttpClient client = (HttpClient) cache.getCached(getClass(), new String[] { "client" });
    if (client != null)
        return client;
    client = new HttpClient(manager);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials((String) creds.getCredential(ServicesStorageGenerator.CRED_USERID),
                    (String) creds.getCredential(ServicesStorageGenerator.CRED_PASSWORD)));
    client.getParams().setAuthenticationPreemptive(true);
    cache.setCached(getClass(), new String[] { "client" }, client);
    return client;
}

From source file:org.cryptomator.ui.controllers.WelcomeController.java

private void checkForUpdates() {
    checkForUpdatesStatus.setText(localization.getString("welcome.checkForUpdates.label.currentlyChecking"));
    checkForUpdatesIndicator.setVisible(true);
    asyncTaskService.asyncTaskOf(() -> {
        final HttpClient client = new HttpClient();
        final HttpMethod method = new GetMethod("https://cryptomator.org/downloads/latestVersion.json");
        client.getParams().setParameter(HttpClientParams.USER_AGENT,
                "Cryptomator VersionChecker/" + ApplicationVersion.orElse("SNAPSHOT"));
        client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        client.getParams().setConnectionManagerTimeout(5000);
        client.executeMethod(method);//from  w w w . j a va2s.  c o  m
        final InputStream responseBodyStream = method.getResponseBodyAsStream();
        if (method.getStatusCode() == HttpStatus.SC_OK && responseBodyStream != null) {
            final byte[] responseData = IOUtils.toByteArray(responseBodyStream);
            final ObjectMapper mapper = new ObjectMapper();
            final Map<String, String> map = mapper.readValue(responseData,
                    new TypeReference<HashMap<String, String>>() {
                    });
            if (map != null) {
                this.compareVersions(map);
            }
        }
    }).andFinally(() -> {
        checkForUpdatesStatus.setText("");
        checkForUpdatesIndicator.setVisible(false);
    }).run();
}

From source file:org.customer.AbstractCustomerTag.java

protected HttpClient getHttpClient() {
    HttpClient client = new HttpClient();

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(getRepoHost(), getRepoPort()),
            new UsernamePasswordCredentials(getRepoUsername(), getRepoPassword()));

    return client;
}

From source file:org.deegree.commons.utils.net.HttpUtils.java

private static void handleProxies(String protocol, HttpClient client, String host) {
    TreeSet<String> nops = new TreeSet<String>();

    String proxyHost = getProperty((protocol == null ? "" : protocol + ".") + "proxyHost");

    String proxyUser = getProperty((protocol == null ? "" : protocol + ".") + "proxyUser");
    String proxyPass = getProperty((protocol == null ? "" : protocol + ".") + "proxyPassword");

    if (proxyHost != null) {
        String nop = getProperty((protocol == null ? "" : protocol + ".") + "noProxyHosts");
        if (nop != null && !nop.equals("")) {
            nops.addAll(asList(nop.split("\\|")));
        }/*from  w  w  w .  j a  v  a 2 s  .  c om*/
        nop = getProperty((protocol == null ? "" : protocol + ".") + "nonProxyHosts");
        if (nop != null && !nop.equals("")) {
            nops.addAll(asList(nop.split("\\|")));
        }

        int proxyPort = parseInt(getProperty((protocol == null ? "" : protocol + ".") + "proxyPort"));

        HostConfiguration hc = client.getHostConfiguration();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Found the following no- and nonProxyHosts: {}", nops);
        }

        if (proxyUser != null) {
            Credentials creds = new UsernamePasswordCredentials(proxyUser, proxyPass);
            client.getState().setProxyCredentials(AuthScope.ANY, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        if (!nops.contains(host)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using proxy {}:{}", proxyHost, proxyPort);
                if (protocol == null) {
                    LOG.debug("This overrides the protocol specific settings, if there were any.");
                }
            }
            hc.setProxy(proxyHost, proxyPort);
            client.setHostConfiguration(hc);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Proxy was set, but {} was contained in the no-/nonProxyList!", host);
                if (protocol == null) {
                    LOG.debug("If a protocol specific proxy has been set, it will be used anyway!");
                }
            }
        }
    }

    if (protocol != null) {
        handleProxies(null, client, host);
    }
}