Sunday, January 5, 2014

HTTPClient PoolingHttpClientConnectinManager Example for Better Performance

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpClientExample{

    public static void main(String[] args) throws IOException {
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
        String datef = sdf.format(new Date());
        System.out.println(datef);
        ArrayList yrls = new ArrayList();
        String url = "www.yahoo.com";
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(10);
        cm.setDefaultMaxPerRoute(10);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
    
        long time1 = System.nanoTime();
        
        //    HttpClient httpClient = new DefaultHttpClient();
            HttpHead get = new HttpHead(url);
            HttpResponse resp = httpClient.execute(get);
            System.out.println(url +" :::"+ resp.getStatusLine().getStatusCode());
            
               long time2 = System.nanoTime();
        
        System.out.println("Difference = " + (time2 - time1));
        httpClient.close();
        
    }

  }

No comments: