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";
    }
}

这里写图片描述

阅读更多
文章标签: springboot httpclient
个人分类: JAVAEE技术博客
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

springboot 如何集成httpClient

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭