springboot 如何集成httpClient

使用Spring集成httpclient时,需要复杂的配置文件spring管理httpclient。而使用SpringBoot来集成httpclient,我们只需要几个注解,一个java文件就能搞定。

pox.xml文件:

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

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

        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.3.1version>
        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 map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry 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";
    }
}

springboot 如何集成httpClient_第1张图片

你可能感兴趣的:(JAVAEE技术博客)