Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

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

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:org.openrepose.commons.utils.http.ServiceClient.java

private HttpClient getClientWithBasicAuth() throws ServiceClientException {
    HttpClientResponse clientResponse = null;

    try {/*w w  w. j a v  a 2  s. c om*/

        clientResponse = httpClientService.getClient(connectionPoolId);
        final HttpClient client = clientResponse.getHttpClient();

        if (!StringUtilities.isEmpty(targetHostUri) && !StringUtilities.isEmpty(username)
                && !StringUtilities.isEmpty(password)) {

            client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(targetHostUri, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(username, password));
            client.getParams().setParameter("http.authentication.credential-provider", credsProvider);

        }

        return client;

    } catch (HttpClientNotFoundException e) {
        LOG.error("Failed to obtain an HTTP default client connection");
        throw new ServiceClientException("Failed to obtain an HTTP default client connection", e);
    } finally {
        if (clientResponse != null) {
            httpClientService.releaseClient(clientResponse);
        }
    }

}

From source file:com.alu.e3.gateway.loadbalancer.E3HttpClientConfigurer.java

@Override
public void configureHttpClient(HttpClient httpClient) {

    ClientConnectionManager clientConnectionManager = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();

    // set Connection Pool Manager
    if (clientConnectionManager instanceof ThreadSafeClientConnManager) {
        setThreadSafeConnectionManager(clientConnectionManager);
    } else {//www .  j a v  a 2s  . c  o  m
        LOGGER.error(
                "The given settings for the HttpClient connection pool will be ignored: Unsupported implementation");
    }

    // set HttpClient global setting
    HttpConnectionParamBean httpConnectionParamBean = new HttpConnectionParamBean(params);
    if (getSocketTimeOut() != null) {
        httpConnectionParamBean.setSoTimeout(getSocketTimeOut());
    }
    // set HttpClient global connection timeout      
    if (getConnectionTimeOut() != null) {
        httpConnectionParamBean.setConnectionTimeout(getConnectionTimeOut());
    }

    // set HttpClient Proxy settings
    if (getForwardProxy() != null) {
        setForwardProxy(httpClient, params);
    }
}

From source file:hornet.framework.technical.HTTPClientParameterBuilderTest.java

/**
 * Test load http param to http client from config.
 *///from  w w  w. j av a  2 s. co  m
@Ignore
@Test
public void testParamsBienPrisEnCompte() {

    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "DEBUG");

    final HttpClient httpClient = new DefaultHttpClient();

    HTTPClientParameterBuilder.loadHttpParamToHttpClientFromConfig(httpClient, "http-parameters");

    assertEquals("mozilla", httpClient.getParams().getParameter("http.useragent"));

    final HttpGet method = new HttpGet("http://www.google.com");

    try {
        final HttpHost targetHost = new HttpHost("www.google.com", 80, "http");
        final HttpResponse httpResponse = httpClient.execute(targetHost, method);
        final int statusCode = httpResponse.getStatusLine().getStatusCode();
        assertEquals(HttpStatus.SC_OK, statusCode);

        final InputStream responseBody = httpResponse.getEntity().getContent();

        assertNotNull(responseBody);

    } catch (final Exception e) {
        fail("Fatal transport error: " + e.getMessage());
    }

}

From source file:ilarkesto.net.ApacheHttpDownloader.java

protected void initializeClient(HttpClient client) {
    HttpParams params = client.getParams();
    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
    HttpClientParams.setRedirecting(params, false);

    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {//from  w  w  w.j a v a2  s. c o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * //from   w  ww  .  j  a v a2  s. c om
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        // ??APN
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ???
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}

From source file:es.eucm.eadventure.editor.plugin.vignette.ServerProxy.java

private HttpClient getProxiedHttpClient() {

    HttpClient hc = new DefaultHttpClient();
    HttpHost hh = null;//from   w w w  . j a v  a 2 s.  co  m
    if (!requestedProxy) {
        requestedProxy = true;
        hh = ProxySetup.buildHttpProxy(null);
    } else {
        hh = currentProxy;
    }
    if (hh != null) {
        hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hh);
    }
    return hc;
}

From source file:eu.comvantage.dataintegration.DHMConnector.java

public HttpResponse query(String location, String arguments) {
    HttpResponse response = null;/* w ww  .j  a  v  a2s.c o m*/
    String queryString = location + "?" + arguments;
    queryString = endpoint.getEndpointURL() + "/" + queryString;

    try {
        HttpGet httpGet = new HttpGet(queryString);

        //      ByteArrayOutputStream b_out = new ByteArrayOutputStream();
        //      OutputStreamWriter wr = new OutputStreamWriter(b_out);
        //      wr.write(queryString);
        //      wr.flush();
        //      byte[] bytes = b_out.toByteArray() ;
        //      AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes) ;
        //      eqEntity.setContentType("application/x-www-form-urlencoded") ;
        //      reqEntity.setContentEncoding(HTTP.UTF_8) ;
        //      httpPost.setEntity(reqEntity) ;
        HttpClient httpclient = new DefaultHttpClient();

        //set proxy if defined
        if (System.getProperty("http.proxyHost") != null) {
            HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"),
                    Integer.valueOf(System.getProperty("http.proxyPort")), "http");
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        try {
            System.out.println("DHMConnector, Command: " + queryString);
            response = httpclient.execute(httpGet);
            int responseCode = response.getStatusLine().getStatusCode();
            String responseMessage = response.getStatusLine().getReasonPhrase();

            if (responseCode == 204)
                System.out.println("DHMConnector response: NO_CONTENT_204");
            if (responseCode == 200)
                System.out.println("DHMConnector response: OK_200");
            if (responseCode == 404)
                System.out.println("DHMConnector response: NOT_FOUND_404");

            //wr.close();
        } catch (IOException ex) {
            response = null;
            //throw new UpdateException(ex);
        }

    } catch (Exception e) {
        System.out.println("DHMConnector: Can't build HTTP GET object, arguments string is corrupted");
        //e.printStackTrace();
    }
    return response;
}

From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java

@Override
public void onStart(Intent intent, final int startId) {
    super.onStart(intent, startId);

    if (!sending.compareAndSet(false, true)) {
        Log.i(TAG, "Send already in progress, skipping intent");
    }/*www  .  jav a2  s.  c om*/

    final TiAnalyticsService self = this;

    Thread t = new Thread(new Runnable() {

        public void run() {
            Log.i(TAG, "Analytics Service Started");
            try {

                if (connectivityManager == null) {
                    Log.w(TAG, "Connectivity manager not available.");
                    stopSelf(startId);
                    return;
                }
                TiAnalyticsModel model = new TiAnalyticsModel(self);
                if (!model.hasEvents()) {
                    Log.d(TAG, "No events to send.", Log.DEBUG_MODE);
                    stopSelf(startId);
                    return;
                }

                while (model.hasEvents()) {
                    if (canSend()) {
                        LinkedHashMap<Integer, JSONObject> events = model
                                .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK);

                        int len = events.size();
                        int[] eventIds = new int[len];
                        Iterator<Integer> keys = events.keySet().iterator();

                        JSONArray records = new JSONArray();
                        // build up data to send and records to delete on success
                        for (int i = 0; i < len; i++) {
                            int id = keys.next();
                            // ids are kept even on error JSON to prevent unrestrained growth
                            // and a queue blocked by bad records.
                            eventIds[i] = id;
                            records.put(events.get(id));

                            if (Log.isDebugModeEnabled()) {
                                JSONObject obj = events.get(id);
                                Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = "
                                        + obj.getString("ts"));
                            }
                        }
                        boolean deleteEvents = true;
                        if (records.length() > 0) {
                            if (Log.isDebugModeEnabled()) {
                                Log.d(TAG, "Sending " + records.length() + " analytics events.");
                            }
                            try {
                                String jsonData = records.toString() + "\n";
                                String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL
                                        : ANALYTICS_URL + TiApplication.getInstance().getAppGUID();

                                HttpPost httpPost = new HttpPost(postUrl);
                                StringEntity entity = new StringEntity(jsonData);
                                entity.setContentType("text/json");
                                httpPost.setEntity(entity);

                                HttpParams httpParams = new BasicHttpParams();
                                HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property
                                //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property
                                HttpClient client = new DefaultHttpClient(httpParams);

                                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                                client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

                                @SuppressWarnings("unused")
                                String response = client.execute(httpPost, responseHandler);
                            } catch (Throwable t) {
                                Log.e(TAG, "Error posting events: " + t.getMessage(), t);
                                deleteEvents = false;
                                records = null;
                                break;
                            }
                        }

                        records = null;

                        if (deleteEvents) {
                            model.deleteEvents(eventIds);
                        }

                        events.clear();
                    } else {
                        Log.w(TAG, "Network unavailable, can't send analytics");
                        //TODO reset alarm?
                        break;
                    }
                }

                Log.i(TAG, "Stopping Analytics Service");
                stopSelf(startId);
            } catch (Throwable t) {
                Log.e(TAG, "Unhandled exception in analytics thread: ", t);
                stopSelf(startId);
            } finally {
                if (!sending.compareAndSet(true, false)) {
                    Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE);
                }
            }
        }
    });
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:com.zrlh.llkc.funciton.Http_Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from   www  .j av  a2 s  .  co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Http_Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Http_Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}