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

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

Introduction

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

Prototype

public DefaultHttpClient(final ClientConnectionManager conman, final HttpParams params) 

Source Link

Document

Creates a new HTTP client from parameters and a connection manager.

Usage

From source file:httpclient.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpclient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
            "http://jakarta.apache.org/commons/httpclient/",
            "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

    IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
    connEvictor.start();/*from  w  ww .j  a  va 2 s. c o m*/

    for (int i = 0; i < urisToGet.length; i++) {
        String requestURI = urisToGet[i];
        HttpGet req = new HttpGet(requestURI);

        System.out.println("executing request " + requestURI);

        HttpResponse rsp = httpclient.execute(req);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            entity.consumeContent();
        }
    }

    // Sleep 10 sec and let the connection evictor do its job
    Thread.sleep(20000);

    // Shut down the evictor thread
    connEvictor.shutdown();
    connEvictor.join();

    // 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:httpclient.client.ClientExecuteDirect.java

public static void main(String[] args) throws Exception {

    HttpHost target = new HttpHost("www.baidu.com", 80, "http");

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

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

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

    ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target);

    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]);
    }/*from  w  w  w  . j  ava 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:com.hilatest.httpclient.apacheexample.ClientMultiThreadedExecution.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core/",
            "http://hc.apache.org/httpcomponents-client/", "http://svn.apache.org/viewvc/httpcomponents/" };

    // create a thread for each URI
    GetThread[] threads = new GetThread[urisToGet.length];
    for (int i = 0; i < threads.length; i++) {
        HttpGet httpget = new HttpGet(urisToGet[i]);
        threads[i] = new GetThread(httpClient, httpget, i + 1);
    }//from w w  w  . j  a  v a2 s.c o  m

    // start the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].start();
    }

    // join the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].join();
    }

    // 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:com.hilatest.httpclient.apacheexample.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("issues.apache.org", 443, "https");
    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "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]);
    }//from   ww w .j  av a 2  s .c o m
    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:httpclient.client.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("vote.sun0769.com/include/code.asp?s=youthnet&aj=0.70161835174741", 80,
            "http");
    HttpHost proxy = new HttpHost("59.36.98.154", 80, "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, "GB2312");
    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 w w.jav a2s.c o  m
    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:pt.ua.tm.neji.web.test.TestREST.java

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*  w  w w  .j  a v  a2  s.com*/

    MySSLSocketFactory 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, "utf-8");

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

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt";

    // POST
    CloseableHttpClient client = new DefaultHttpClient(ccm, params);

    HttpPost post = new HttpPost(url);
    //post.setHeader("Content-Type", "application/json");

    List<NameValuePair> keyValuesPairs = new ArrayList();
    //keyValuesPairs.add(new BasicNameValuePair("format", "neji"));
    keyValuesPairs.add(new BasicNameValuePair("fromFile", "false"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}"));
    keyValuesPairs.add(new BasicNameValuePair("text", text));
    keyValuesPairs.add(new BasicNameValuePair("crlf", "false"));
    post.setEntity(new UrlEncodedFormEntity(keyValuesPairs));

    HttpResponse response = client.execute(post);

    String result = IOUtils.toString(response.getEntity().getContent());

    System.out.println(result);
}

From source file:com.subgraph.vega.internal.http.requests.BasicHttpClientFactory.java

static HttpClient createHttpClient() {
    final HttpParams params = createHttpParams();
    final ClientConnectionManager ccm = createConnectionManager(params);
    final DefaultHttpClient client = new DefaultHttpClient(ccm, params);

    client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
    client.clearRequestInterceptors();/*from w  w  w.  j a v a2s  .  com*/
    client.clearResponseInterceptors();
    client.addRequestInterceptor(new RequestCopyHeadersInterceptor());
    return client;
}

From source file:Main.java

private static void ensureHttpClient() {
    if (httpClient != null)
        return;//from   w w w.j  a  v  a 2  s .  c  om

    BasicHttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 45000);
    HttpConnectionParams.setSoTimeout(params, 30000);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    try {
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } catch (Exception e) {
        Log.w(TAG, "Unable to register HTTPS socket factory: " + e.getLocalizedMessage());
    }

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, registry);
    httpClient = new DefaultHttpClient(connManager, params);
}

From source file:org.devtcg.five.util.HttpUtils.java

public static HttpClient newHttpClient() {
    HttpParams params = new BasicHttpParams();

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    return new DefaultHttpClient(cm, params);
}

From source file:Main.java

public static DefaultHttpClient getDefaultHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params);

    HttpConnectionParams.setSoTimeout(defaultHttpClient.getParams(), SOCKET_TIME_OUT);
    HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), CONNECTION_TIME_OUT);
    defaultHttpClient.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 10);
    HttpClientParams.setCookiePolicy(defaultHttpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpProtocolParams.setUserAgent(defaultHttpClient.getParams(),
            "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.18) Gecko/20110628 Ubuntu/10.04 (lucid) Firefox/3.6.18");
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
    return defaultHttpClient;
}