springboot 如何集成httpClient

使用Spring集成httpclient時,需要複雜的配置文件spring管理httpclient。而使用SpringBoot來集成httpclient,我們只需要幾個註解,一個java文件就能搞定。

pox.xml文件:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1</version>
        </dependency>

首先在與SpringBoot主配置同級的目錄下建立一個class。

@Configuration public class HttpClient {

  @Value("${http.maxTotal}")
private Integer maxTotal;

@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;

@Value("${http.connectTimeout}")
private Integer connectTimeout;

@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;

@Value("${http.socketTimeout}")
private Integer socketTimeout;

@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled;

@Bean(name = "httpClientConnectionManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
    httpClientConnectionManager.setMaxTotal(maxTotal);
    httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    return httpClientConnectionManager;
}

@Bean(name = "httpClientBuilder")
public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager

httpClientConnectionManager){

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.setConnectionManager(httpClientConnectionManager);

    return httpClientBuilder;
}

@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder")

HttpClientBuilder httpClientBuilder){
return httpClientBuilder.build();
}

@Bean(name = "builder")
public RequestConfig.Builder getBuilder(){
    RequestConfig.Builder builder = RequestConfig.custom();
    return builder.setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setSocketTimeout(socketTimeout)
            .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
}

@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
    return builder.build();
}   }

創建一個httpClientAPIService

@Component
public class HttpAPIService {

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;


    /**
     * 不帶參數的get請求,如果狀態碼爲200,則返回body,如果不爲200,則返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 聲明 http get 請求
        HttpGet httpGet = new HttpGet(url);

        // 裝載配置信息
        httpGet.setConfig(config);

        // 發起請求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判斷狀態碼是否爲200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回響應體的內容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 帶參數的get請求,如果狀態碼爲200,則返回body,如果不爲200,則返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍歷map,拼接請求參數
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 調用不帶參數的get請求
        return this.doGet(uriBuilder.build().toString());

    }

}

接下來寫一個測試接口:

@RestController
public class HttpClientController {

    @Resource
    private HttpAPIService httpAPIService;

    @RequestMapping("httpclient")
    public String test() throws Exception {
        String str = httpAPIService.doGet("http://www.baidu.com");
        System.out.println(str);
        return "hello";
    }
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章