小技巧:利用HC fluent API 優雅地使用Apache HttpClient

Apache HttpClient功能強大,於http客戶端操作有非常豐富的語義的支持。但是要在高併發、大流量的生產環境中健壯地使用好Apache HttpClient,還是要考慮很多場景的,比如使用連接池,使用代理,重試策略等等,這些都需要用各種API做各種繁瑣的配置。我在使用過程中也嘗試自己再封裝一層,但考慮到自己的遇到的場景不多,可能封裝的時候考慮不夠充分,沒有按照最佳實踐來做。還是先找找別人封裝過的,借鑑學習下。

一輪google下,才發現其實Apache HttpClient 官方就有一個子項目,HC fluent API,提供鏈式調用風格的API,支持常用的HTTP Method,支持proxy,支持添加Header,支持異步API,如果想做其他個性化配置,也預留了API,讓用戶使用自己配置的HttpClient。

看下以下兩段示例代碼感受一下:

  • GET 示例
// Execute a GET with timeout settings and return response content as String.
Request.Get("http://somehost/")
        .connectTimeout(1000)
        .socketTimeout(1000)
        .execute().returnContent().asString();
  • POST 示例
// Execute a POST with a custom header through the proxy containing a request body
// as an HTML form and save the result to the file
Request.Post("http://somehost/some-form")
        .addHeader("X-Custom-header", "stuff")
        .viaProxy(new HttpHost("myproxy", 8080))
        .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
        .execute().saveContent(new File("result.dump"));

在上面我們沒有看到連接池的配置代碼,實際上是因爲fluent api 提供了默認的配置了。

	final static PoolingHttpClientConnectionManager CONNMGR;
    final static HttpClient CLIENT;

    static {
        ...
        CONNMGR = new PoolingHttpClientConnectionManager(sfr);
        CONNMGR.setDefaultMaxPerRoute(100);
        CONNMGR.setMaxTotal(200);
        CONNMGR.setValidateAfterInactivity(1000);
        CLIENT = HttpClientBuilder.create()
                .setConnectionManager(CONNMGR)
                .build();
    }

    public static Executor newInstance() {
        return new Executor(CLIENT);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章