Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getParams.

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:com.senseidb.dataprovider.http.HttpsClientDecorator.java

public static DefaultHttpClient decorate(DefaultHttpClient base) {
    try {/* w w  w.jav a  2 s.co m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        return null;
    }
}

From source file:fr.eolya.utils.http.HttpLoader.java

public static Map<String, String> getAuthCookies(int authMode, String authLogin, String authPasswd,
        String authParam, String proxyHost, String proxyPort, String proxyExclude, String proxyUser,
        String proxyPassword) {/*from w  w  w. ja  va2  s . com*/

    if (authMode == 0)
        return null;

    Map<String, String> authCookies = null;
    String[] aAuthParam = authParam.split("\\|");

    // http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // Proxy
    setProxy(httpClient, aAuthParam[0], proxyHost, proxyPort, proxyExclude, proxyUser, proxyPassword);

    HttpPost httpPost = new HttpPost(aAuthParam[0]);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        for (int i = 1; i < aAuthParam.length; i++) {
            String[] aPair = aAuthParam[i].split("=");
            aPair[1] = aPair[1].replaceAll("\\$\\$auth_login\\$\\$", authLogin);
            aPair[1] = aPair[1].replaceAll("\\$\\$auth_passwd\\$\\$", authPasswd);
            nameValuePairs.add(new BasicNameValuePair(aPair[0], aPair[1]));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpPost.setHeader("ContentType", "application/x-www-form-urlencoded");
        HttpResponse response = httpClient.execute(httpPost, localContext);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();
        }

        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
        if (!cookies.isEmpty()) {
            authCookies = new HashMap<String, String>();
            for (Cookie c : cookies) {
                // TODO: What about the path, the domain ???
                authCookies.put(c.getName(), c.getValue());
            }
        }
        httpPost.abort();
    } catch (ClientProtocolException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
    return authCookies;
}

From source file:org.apache.olingo.client.core.http.DefaultHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
    return client;
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(Certificate[] sslCertificate, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;
    HttpHost proxy;//from   w  w w .  j  a  v a 2  s.c  o m

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:org.osmsurround.ae.osmrequest.OsmRequestTemplate.java

protected DefaultHttpClient createHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
    httpClient.getParams().setBooleanParameter("http.authentication.preemptive", true);
    return httpClient;
}

From source file:sand.actionhandler.weibo.UdaClient.java

public static String syn(String method, String machineno, String params) {
    String content = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w w  w.  java  2s.c  o m*/
        httpclient = createHttpClient();
        //      HttpGet httpget = new HttpGet("http://www.broken-server.com/");
        // 

        HttpGet httpget = new HttpGet(SERVER + method + "?no=" + machineno + "&" + params);

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        //           httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        // Execute HTTP request
        //System.out.println("executing request " + httpget.getURI());

        // DefaultHttpClient httpclient = new DefaultHttpClient();
        // cookie store
        CookieStore cookieStore = new BasicCookieStore();

        addCookie(cookieStore);
        // 
        httpclient.setCookieStore(cookieStore);

        logger.info("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        //            System.out.println("----------------------------------------");
        //            System.out.println(response.getStatusLine());
        //            System.out.println(response.getLastHeader("Content-Encoding"));
        //            System.out.println(response.getLastHeader("Content-Length"));
        //            System.out.println("----------------------------------------");

        HttpEntity entity = response.getEntity();
        //System.out.println(entity.getContentType());

        if (entity != null) {
            content = EntityUtils.toString(entity);
            //                System.out.println(content);
            //                System.out.println("----------------------------------------");
            //                System.out.println("Uncompressed size: "+content.length());
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return content;
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Returns the preconfigured http client,
 * using CertificateVerificationService, timeouts, user-agent,
 * hostname verifier, proxy settings are used from global java settings,
 * if protected site is hit asks for credentials
 * using util.swing.AuthenticationWindow.
 * @param usernamePropertyName the property to use to retrieve/store
 * username value if protected site is hit, for username
 * ConfigurationService service is used.
 * @param passwordPropertyName the property to use to retrieve/store
 * password value if protected site is hit, for password
 * CredentialsStorageService service is used.
 * @param credentialsProvider if not null provider will bre reused
 * in the new client/*from   w  w  w . jav  a 2  s .c om*/
 * @param address the address we will be connecting to
 */
public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName,
        final String address, CredentialsProvider credentialsProvider) throws IOException {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    HttpProtocolParams.setUserAgent(httpClient.getParams(),
            System.getProperty("sip-communicator.application.name") + "/"
                    + System.getProperty("sip-communicator.version"));

    SSLContext sslCtx;
    try {
        sslCtx = HttpUtilActivator.getCertificateVerificationService()
                .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address));
    } catch (GeneralSecurityException e) {
        throw new IOException(e.getMessage());
    }

    // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER:
    // the SSL context obtained from the certificate service takes care of
    // certificate validation
    try {
        Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx));
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Throwable t) {
        logger.error("Error creating ssl socket factory", t);
    }

    // set proxy from default jre settings
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (credentialsProvider == null)
        credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName);
    httpClient.setCredentialsProvider(credentialsProvider);

    // enable retry connecting with default retry handler
    // when connecting has prompted for authentication
    // connection can be disconnected nefore user answers and
    // we need to retry connection, using the credentials provided
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    return httpClient;
}

From source file:org.apache.olingo.samples.client.core.http.ParametersHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final DefaultHttpClient httpClient = super.create(method, uri);

    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    final int timeout = 1000;
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), timeout);
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), timeout);

    return httpClient;
}

From source file:org.xwiki.extension.repository.xwiki.internal.httpclient.DefaultHttpClientFactory.java

@Override
public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
    }/*from   www .  j a  va 2s  .c  o  m*/

    return httpClient;
}

From source file:com.google.api.client.http.apache.ApacheHttpTransportTest.java

private void checkDefaultHttpClient(DefaultHttpClient client) {
    HttpParams params = client.getParams();
    assertTrue(client.getConnectionManager() instanceof ThreadSafeClientConnManager);
    assertEquals(8192, params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1));
    DefaultHttpRequestRetryHandler retryHandler = (DefaultHttpRequestRetryHandler) client
            .getHttpRequestRetryHandler();
    assertEquals(0, retryHandler.getRetryCount());
    assertFalse(retryHandler.isRequestSentRetryEnabled());
}