Example usage for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT

List of usage examples for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT

Introduction

In this page you can find the example usage for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT.

Prototype

String CONNECTION_TIMEOUT

To view the source code for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT.

Click Source Link

Usage

From source file:com.example.AsyncClientHttpExchangeFutureCallback.java

public static void main(String[] args) throws Exception {
    HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    httpclient.start();//from  w  w w.  j av  a2 s. co  m
    try {
        HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.shutdown();
    }
    System.out.println("Done");
}

From source file:bundestagswahl.benchmark.BWBenchmark.java

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

    resultTime = new double[6];

    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter URL: ");
    serverUrl = scanner.nextLine();/*  w  ww. j ava 2 s. c  o  m*/
    System.out.print("Please enter number of terminals: ");
    numberTerminals = scanner.nextInt();
    System.out.print("Please enter number of requests: ");
    numberRequests = scanner.nextInt();
    System.out.print("Please enter delay between two requests in seconds: ");
    requestDelay = scanner.nextDouble();
    scanner.close();

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(numberTerminals);
    HttpClient httpclient = new DefaultHttpClient(cm);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    try {
        final CountDownLatch latch = new CountDownLatch(numberTerminals);
        for (int i = 0; i < numberTerminals; i++) {
            BenchmarkTerminal terminal = new BenchmarkTerminal(httpclient, latch, serverUrl, numberRequests,
                    requestDelay);
            terminal.start();
        }
        latch.await();
        httpclient.getConnectionManager().shutdown();
    } finally {

    }

    printResultTimes();
    System.out.println(" ");
    System.out.println("Done");
}

From source file:wh.contrib.RewardOptimizerHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT,
                    "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    RequestCount requestCount = new RequestCount(1);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }/*from w ww .ja va 2  s  .  c  o m*/
            System.out.println("Shutdown");
        }

    });
    t.start();

    List<SessionRequest> reqs = new ArrayList<SessionRequest>();
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.yahoo.com", 80), 
    //                null, 
    //                new HttpHost("www.yahoo.com"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.google.com", 80), 
    //                null,
    //                new HttpHost("www.google.ch"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.apache.org", 80), 
    //                null,
    //                new HttpHost("www.apache.org"),
    //                null));

    reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null,
            new HttpHost("www.wowhead.com"), null));

    // Block until all connections signal
    // completion of the request execution
    synchronized (requestCount) {
        while (requestCount.getValue() > 0) {
            requestCount.wait();
        }
    }

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    //CountDownLatch requestCount = new CountDownLatch(3);
    CountDownLatch requestCount = new CountDownLatch(1);

    BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//from w  w  w  . j a  va  2s .  c  o m
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[1];
    reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null,
            new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount));
    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    CountDownLatch requestCount = new CountDownLatch(3);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//  w  w w . j av  a 2 s .  c  o m
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[3];
    reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"),
            new MySessionRequestCallback(requestCount));
    reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null,
            new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount));
    reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null,
            new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount));

    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  /*from  w  ww.  j  a va2  s  .  co m*/
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(target + "->" + ex);
                        }

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:Main.java

public static HttpClient getHttpClient() {

    if (httpClient != null) {
        return httpClient;
    }/*from   www .j  a  v  a  2  s.co m*/

    synchronized (HTTP_CLIENT) {
        HttpParams defaultParams = new BasicHttpParams();
        defaultParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
        defaultParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
        defaultParams.setLongParameter(ConnManagerPNames.TIMEOUT, 6000);

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

        ClientConnectionManager connMgr = new ThreadSafeClientConnManager(defaultParams, scheme);

        httpClient = new DefaultHttpClient(connMgr, defaultParams);
    }

    return httpClient;
}

From source file:no.kantega.kwashc.server.test.HttpClientUtil.java

static HttpClient getHttpClient() {
    HttpClient httpClient = new DefaultHttpClient();
    // timeout: 5 seconds
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * 1000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5 * 1000);
    return httpClient;
}

From source file:com.sunhz.projectutils.httputils.HttpClientUtils.java

/**
 * get access to the network, you need to use in the sub-thread
 *
 * @param url url//from   ww  w. j  av  a  2s .c  o m
 * @return response inputStream
 * @throws IOException In the case of non-200 status code is returned, it would have thrown
 */
public static InputStream getInputStream(String url) throws IOException {
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Constant.TimeInApplication.NET_TIMEOUT);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constant.TimeInApplication.NET_TIMEOUT);
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity().getContent();
    } else {
        throw new IllegalArgumentException("getInputStreamInSubThread response status code is "
                + response.getStatusLine().getStatusCode());
    }
}

From source file:org.carrot2.util.httpclient.HttpClientFactory.java

/**
 * @param timeout Timeout in milliseconds.
 * @return Returns a client with sockets configured to timeout after some sensible
 *         time.//from  w  w w.ja v a  2 s  .  c  om
 */
public static DefaultHttpClient getTimeoutingClient(int timeout) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    configureProxy(httpClient);

    // Setup defaults.
    httpClient.setReuseStrategy(new NoConnectionReuseStrategy());

    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_LINGER, 0);

    return httpClient;
}