2010年5月13日 星期四

HttpClient 4

HttpClient 4 出囉, 先自己去官網看看吧, 用起來比 3 方便, 好用, tutorial 也有完整的教學, 這裡不多說哩.



以下提供 4.1 beta 版的 util, 支援 multithread, 一個專案共用一個挺方便的.



public class HttpUtil {

    private static HttpUtil http = new HttpUtil();
    private DefaultHttpClient client;

    public synchronized DefaultHttpClient getClient() {
        return client;
    }

    private HttpUtil() {
        configureClient();
    }

    public static HttpUtil getInstance() {
        return http;
    }


    private void configureClient() {

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


        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
                schemeRegistry);
        // Increase max total connection to 200
        cm.setMaxTotalConnections(200);
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 8080);
        cm.setMaxForRoute(new HttpRoute(localhost), 50);
        client = new DefaultHttpClient(cm);
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,
                true));
    }

    public void shutdownHttp() {
        client.getConnectionManager().shutdown();
    }

    public void closeExpiredConns() {
        client.getConnectionManager().closeExpiredConnections();
    }

    public void closeIdleConns() {
        client.getConnectionManager().closeIdleConnections(50L,
                TimeUnit.SECONDS);
    }

沒有留言:

張貼留言