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.example.week04.GcmIntentService.java

private void getArticleInBackground(final String keyword) {
    new AsyncTask<Void, Void, Void>() {
        private String resultMessage = "";

        @Override/*from  w w  w .  j  av a  2  s. c  o m*/
        protected Void doInBackground(Void... params) {
            String serverURL = new Settings().getServerURL();
            String URL = serverURL + "getArticle/" + keyword;
            DefaultHttpClient client = new DefaultHttpClient();
            String result;
            try {
                // Make connection to server.
                Log.i("Connection", "Make connection to server");
                HttpParams connectionParams = client.getParams();
                HttpConnectionParams.setConnectionTimeout(connectionParams, 5000);
                HttpConnectionParams.setSoTimeout(connectionParams, 5000);
                HttpGet httpGet = new HttpGet(URL);

                // Get response and parse entity.
                Log.i("Connection", "Get response and parse entity.");
                HttpResponse responsePost = client.execute(httpGet);
                HttpEntity resEntity = responsePost.getEntity();

                // Parse result to string.
                Log.i("Connection", "Parse result to string.");
                result = EntityUtils.toString(resEntity);
                result = result.replaceAll("'|&lt;|&quot;|&gt;", "''");
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Connection", "Some error in server!");
                result = "";
            }

            client.getConnectionManager().shutdown(); // Disconnect.

            if (!result.isEmpty()) {
                try {
                    JSONArray articleArray = new JSONArray(result);
                    int arrayLength = articleArray.length();
                    int updatedRow = 0;

                    DBHelper mHelper = new DBHelper(getApplicationContext());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    for (int i = 0; i < arrayLength; i++) {
                        JSONObject articleObject = articleArray.getJSONObject(i);
                        String title = articleObject.getString("Title");
                        String link = articleObject.getString("Link");
                        String date = articleObject.getString("Date");
                        String news = articleObject.getString("News");
                        String content = articleObject.getString("Head");
                        String query = "INSERT INTO ARTICLES(KEYWORD, TITLE, NEWS, DATE, CONTENT, LINK) VALUES('"
                                + keyword + "', '" + title + "', '" + news + "', '" + date + "', '" + content
                                + "', '" + link + "');";
                        try {
                            updatedRow++;
                            db.execSQL(query);
                        } catch (SQLException e) {
                            updatedRow--;
                            Log.i("SQL inserting", "SQL exception in " + i + "th row : duplicated?");
                        }

                    }

                    String thisTime = getThisTime();
                    String query = "UPDATE KEYWORDS SET LASTUPDATE = '" + thisTime + "' WHERE KEYWORD = '"
                            + keyword + "';";
                    db.execSQL(query);

                    mHelper.close();

                    if (updatedRow > 0) {
                        resultMessage = "Article loading complete!";
                        sendNotification(
                                "'" + keyword + "'    " + updatedRow + " !");
                    } else {
                        resultMessage = "Loading complete - No fresh news.";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resultMessage = "Error in article loading - problem in JSONArray?";
                }
            } else {
                resultMessage = "Error in receiving articles!";
            }
            Log.i("JSON parsing", resultMessage);
            return null;
        }
    }.execute(null, null, null);
}

From source file:com.google.pubsub.clients.common.MetricsHandler.java

private void initialize() {
    synchronized (this) {
        try {/* w ww  .  ja  va2 s  . c o  m*/
            HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(
                        Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
            }
            monitoring = new Monitoring.Builder(transport, jsonFactory, credential)
                    .setApplicationName("Cloud Pub/Sub Loadtest Framework").build();
            String zoneId;
            String instanceId;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.addRequestInterceptor(new RequestAcceptEncoding());
                httpClient.addResponseInterceptor(new ResponseContentEncoding());

                HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true);
                HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false);
                HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);

                SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
                schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
                httpClient.setKeepAliveStrategy((response, ctx) -> 30);
                HttpGet zoneIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/zone");
                zoneIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest);
                String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity());
                if (tempZoneId.lastIndexOf("/") >= 0) {
                    zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1);
                } else {
                    zoneId = tempZoneId;
                }
                HttpGet instanceIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/id");
                instanceIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest);
                instanceId = EntityUtils.toString(instanceIdResponse.getEntity());
            } catch (IOException e) {
                log.info("Unable to connect to metadata server, assuming not on GCE, setting "
                        + "defaults for instance and zone.");
                instanceId = "local";
                zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local.
            }

            monitoredResource.setLabels(
                    ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId));
            createMetrics();
        } catch (IOException e) {
            log.error("Unable to initialize MetricsHandler, trying again.", e);
            executor.execute(this::initialize);
        } catch (GeneralSecurityException e) {
            log.error("Unable to initialize MetricsHandler permanently, credentials error.", e);
        }
    }
}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

private HttpClient getHttpClient() {
    if (this.httpClient == null) {
        DefaultHttpClient newDefaultHttpClient = null;

        if (getUsername() != null || getPassword() != null) {
            try {
                final IProxyService proxyService = LiferayCore.getProxyService();

                URI uri = new URI("http://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                IProxyData[] proxyDataForHost = proxyService.select(uri);

                for (IProxyData data : proxyDataForHost) {
                    if (data.getHost() != null && data.getPort() > 0) {
                        SchemeRegistry schemeRegistry = new SchemeRegistry();
                        schemeRegistry.register(
                                new Scheme("http", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
                        cm.setMaxTotal(200);
                        cm.setDefaultMaxPerRoute(20);

                        DefaultHttpClient newHttpClient = new DefaultHttpClient(cm);
                        HttpHost proxy = new HttpHost(data.getHost(), data.getPort());

                        newHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        newDefaultHttpClient = newHttpClient;
                        break;
                    }/*from   ww w  . j  av  a  2 s . c  o m*/
                }

                if (newDefaultHttpClient == null) {
                    uri = new URI("SOCKS://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                    proxyDataForHost = proxyService.select(uri);

                    for (IProxyData data : proxyDataForHost) {
                        if (data.getHost() != null) {
                            DefaultHttpClient newHttpClient = new DefaultHttpClient();
                            newHttpClient.getParams().setParameter("socks.host", data.getHost()); //$NON-NLS-1$
                            newHttpClient.getParams().setParameter("socks.port", data.getPort()); //$NON-NLS-1$
                            newHttpClient.getConnectionManager().getSchemeRegistry().register(
                                    new Scheme("socks", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                            newDefaultHttpClient = newHttpClient;
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                LiferayCore.logError("Unable to read proxy data", e); //$NON-NLS-1$
            }

            if (newDefaultHttpClient == null) {
                newDefaultHttpClient = new DefaultHttpClient();
            }

            this.httpClient = newDefaultHttpClient;
        } else {
            this.httpClient = new DefaultHttpClient();
        }
    }

    return this.httpClient;
}

From source file:com.ibm.sbt.service.basic.ProxyEndpointService.java

@Override
protected DefaultHttpClient getClient(HttpServletRequest request, int timeout) {
    DefaultHttpClient httpClient = super.getClient(request, timeout);
    if (endpoint != null) {
        if (endpoint.isForceTrustSSLCertificate() && requestURI != null) {
            httpClient = SSLUtil.wrapHttpClient(httpClient);
        }/*  ww w  .  j  av a 2  s  .co  m*/
        if (endpoint.isForceDisableExpectedContinue()) {
            httpClient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        }
        String httpProxy = getHttpProxy(endpoint);
        if (StringUtil.isNotEmpty(httpProxy)) {
            httpClient = ProxyDebugUtil.wrapHttpClient(httpClient, httpProxy);
        }
    }
    return httpClient;
}

From source file:org.jboss.jdf.stacks.client.StacksClient.java

private void configureProxy(DefaultHttpClient client) {
    if (actualConfiguration.getProxyHost() != null && !actualConfiguration.getProxyHost().isEmpty()) {
        String proxyHost = actualConfiguration.getProxyHost();
        int proxyPort = actualConfiguration.getProxyPort();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        String proxyUsername = actualConfiguration.getProxyUser();
        if (proxyUsername != null && !proxyUsername.isEmpty()) {
            String proxyPassword = actualConfiguration.getProxyPassword();
            AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);/*  ww w  .  java  2 s  .c o m*/
            client.getCredentialsProvider().setCredentials(authScope, credentials);
        }
    }
}

From source file:com.meh.CopyProxy.java

private HttpResponse download(String url) {
    DefaultHttpClient seed = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry);
    DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
    HttpGet method = new HttpGet(url);
    method.addHeader("Icy-MetaData", "0"); //disable icy metadata since builtin support doesn't like it
    HttpResponse response = null;/*from  ww  w .ja  v a 2  s  .com*/
    try {
        Log.d(tag, "starting download");
        response = http.execute(method);
        Log.d(tag, "downloaded");
    } catch (ClientProtocolException e) {
        Log.e(tag, "Error downloading", e);
    } catch (IOException e) {
        Log.e(tag, "Error downloading", e);
    }
    return response;
}

From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java

@Override
public void initializeHTTPClient(DefaultHttpClient httpClient) {

    // Time out after 30 seconds.
    //TODO Make configurable.
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);

    // Add support for FTP websites (FTP served by HTTP server).
    Scheme ftp = new Scheme("ftp", FTP_PORT, new PlainSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(ftp);

    //TODO make charset configurable instead since UTF-8 is not right
    // charset for URL specifications.  It is used here to overcome
    // so invalid redirect errors, where the redirect target URL is not 
    // URL-Encoded and has non-ascii values, and fails
    // (e.g. like ja.wikipedia.org).
    // Can consider a custom RedirectStrategy too if need be.
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8");

    if (StringUtils.isNotBlank(proxyHost)) {
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
        if (StringUtils.isNotBlank(proxyUsername)) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }/*  ww w.j av a 2 s  .  c  o  m*/
    }

    if (!cookiesDisabled) {
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    }
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    } else if (AUTH_METHOD_BASIC.equalsIgnoreCase(authMethod)) {
        setupBasicDigestAuth(httpClient);
    } else if (AUTH_METHOD_DIGEST.equalsIgnoreCase(authMethod)) {
        setupBasicDigestAuth(httpClient);
    }
    if (userAgent != null) {
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
    }
}

From source file:org.jboss.maven.plugins.qstools.config.ConfigurationProvider.java

private void configureProxy(DefaultHttpClient client) {
    Proxy proxyConfig = null;//  w  ww  . j  a  v  a  2s.c o m
    if (mavenSession.getSettings().getProxies().size() > 0) {
        proxyConfig = mavenSession.getSettings().getProxies().get(0);
    }
    if (proxyConfig != null) {
        HttpHost proxy = new HttpHost(proxyConfig.getHost(), proxyConfig.getPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        String proxyUsername = proxyConfig.getUsername();
        if (proxyUsername != null && !proxyUsername.isEmpty()) {
            String proxyPassword = proxyConfig.getPassword();
            AuthScope authScope = new AuthScope(proxyConfig.getHost(), proxyConfig.getPort());
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            client.getCredentialsProvider().setCredentials(authScope, credentials);
        }
    }
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

protected HttpClient initClient(String useragent) {
    SchemeRegistry schemeRegistry = initSchemeRegistry();
    ClientConnectionManager cm = initConnectionManager(schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm);
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent);
    initDefaultParameters(params);/*from  ww  w.  ja  va 2  s  . c om*/
    return client;
}