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

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

Introduction

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

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:com.quietlycoding.android.reader.util.api.Authentication.java

/**
 * This method returns back to the caller a proper authentication token to
 * use with the other API calls to Google Reader.
 * /*from  ww w  .  j  a v  a2s. com*/
 * @param user
 *            - the Google username
 * @param pass
 *            - the Google password
 * @return sid - the returned authentication token for use with the API.
 * 
 */
public static String getAuthToken(String user, String pass) {
    final NameValuePair username = new BasicNameValuePair("Email", user);
    final NameValuePair password = new BasicNameValuePair("Passwd", pass);
    final NameValuePair service = new BasicNameValuePair("service", "reader");
    final List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(username);
    pairs.add(password);
    pairs.add(service);

    try {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpPost post = new HttpPost(AUTH_URL);
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);

        post.setEntity(entity);

        final HttpResponse response = client.execute(post);
        final HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Server Response: " + response.getStatusLine());

        final InputStream in = respEntity.getContent();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        String result = null;

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("SID")) {
                result = line.substring(line.indexOf("=") + 1);
            }
        }

        reader.close();
        client.getConnectionManager().shutdown();

        return result;
    } catch (final Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}

From source file:net.sf.dvstar.transmission.protocol.TestConnection.java

public static void testConnection() throws Exception {
    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("195.74.67.237", 80, "http");
    HttpHost proxy = new HttpHost("192.168.4.7", 3128, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

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

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + proxy);
    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers = rsp.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i]);
    }/*  w ww  .  j  a  va 2 s .  c om*/
    System.out.println("----------------------------------------");

    if (entity != null) {
        System.out.println(EntityUtils.toString(entity));
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:no.uib.tools.OnthologyHttpClient.java

public static List<String> getTermDescendants(String onthologyName, String term, String relation) {
    List<String> result = new ArrayList<>();
    String queryContent = "";

    onthologySize = getOntologySize(onthologyName);
    String uri = createUri(onthologyName, term, relation);
    //BufferedReader br = getContentBufferedReader(uri);
    //String queryContent = convertBufferedReader(br);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    getRequest.addHeader("accept", "application/json");

    HttpResponse response;/*from   ww w. ja v  a  2  s. c o m*/
    try {
        response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to get the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String line;
        FileWriter fw = new FileWriter("./mod.json");

        while ((line = br.readLine()) != null) {
            fw.write(line);
            queryContent += line;
        }

        fw.close();
        httpClient.getConnectionManager().shutdown();

        char c;
        int matched = 0;
        String mod = "";
        int pos = 0;

        while (pos < queryContent.length()) {
            c = queryContent.charAt(pos);
            pos++;
            if (c == pattern.charAt(matched)) {
                matched++;
                if (matched == pattern.length()) {
                    for (int I = 0; I < 5; I++) {
                        mod += queryContent.charAt(pos);
                        pos++;
                    }
                    result.add(mod);
                    mod = "";
                    matched = 0;
                }
            } else {
                matched = 0;
            }
        }

    } catch (IOException ex) {
        Logger.getLogger(OnthologyHttpClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:core.HttpClient.java

/**
 * downloads the latest file/* w  w w. j a v a 2 s.com*/
 */
public static String downloadUpdatedFile() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpResponse response;
        HttpEntity entity;

        HttpPost httpost = new HttpPost(QUICKTODO_DOWNLOAD_LINK);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("download_update", "true"));

        response = httpclient.execute(httpost);

        entity = response.getEntity();
        if (entity != null) {
            FileOutputStream fos = new FileOutputStream("QuickToDoUpdate.zip");
            entity.writeTo(fos);
            fos.close();
            return "QuickToDoUpdate.zip";
        }
        return null;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

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

public static HttpClient getHttpsClient(byte[] sslCertificateBytes) {
    DefaultHttpClient httpClient;
    Certificate[] sslCertificate;

    httpClient = new DefaultHttpClient();
    try {//  w  ww  . j  a  v a 2  s  . c  o m
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        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);

        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:com.jelastic.JelasticService.java

private static DefaultHttpClient wrapClient(DefaultHttpClient base) {
    try {/*from   w w  w.  j av  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);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        return null;
    }
}

From source file:org.anhonesteffort.flock.test.registration.HttpClientFactoryTest.java

public void testScheme() throws Exception {
    final HttpClientFactory httpFactory = new HttpClientFactory(getInstrumentation().getContext());
    final DefaultHttpClient httpClient = httpFactory.buildClient();
    final SchemeRegistry schemes = httpClient.getConnectionManager().getSchemeRegistry();

    final Scheme httpScheme = schemes.getScheme("http");
    final Scheme httpsScheme = schemes.getScheme("https");

    assertTrue(httpScheme != null && httpsScheme != null);
    assertTrue(schemes.getSchemeNames().size() == 2);

    assertTrue(httpsScheme.getDefaultPort() == 443);
    assertTrue(httpsScheme.getSocketFactory() instanceof SSLSocketFactory);
}

From source file:org.n52.supervisor.checks.json.JsonServiceCheck.java

protected HttpClient createClient() throws Exception {
    DefaultHttpClient result = new DefaultHttpClient();
    SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry();

    SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {

        @Override//w w w.  j  a va2s .c o  m
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }, new AllowAllHostnameVerifier());

    Scheme httpsScheme2 = new Scheme("https", 443, sslsf);
    sr.register(httpsScheme2);

    return result;
}

From source file:com.mama100.rs.client.RESTfulClient.java

public void callHttpClient() throws Exception {
    String keyStoreLoc = "clientKeystore.jks";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc);
    if (is == null) {
        System.out.println("--------------------can't get the resource file " + keyStoreLoc);
    }//from w  w w  .j  a v a  2s.  c o  m
    keyStore.load(is, "cspass".toCharArray());
    /*
     * Send HTTP GET request to query customer info using portable HttpClient
     * object from Apache HttpComponents
     */
    SSLSocketFactory sf = new SSLSocketFactory(keyStore, "ckpass", keyStore);
    Scheme httpsScheme = new Scheme("https", 9000, sf);

    System.out.println("Sending HTTPS GET request to query customer info");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
    HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
    BasicHeader bh = new BasicHeader("Accept", "text/xml");
    httpget.addHeader(bh);

    HttpResponse response = httpclient.execute(httpget);
    System.out.println("-----" + response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    entity.writeTo(System.out);
    httpclient.getConnectionManager().shutdown();
}

From source file:com.rastating.droidbeard.net.HttpClientManager.java

private DefaultHttpClient createThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager manager = client.getConnectionManager();
    HttpParams params = client.getParams();
    ThreadSafeClientConnManager threadSafeManager = new ThreadSafeClientConnManager(params,
            manager.getSchemeRegistry());
    return new DefaultHttpClient(threadSafeManager, params);
}