工具類のHttpClient各種要求パッケージ

17526 ワード

一、本道の導入依存
        
        
            org.apache.httpcomponents
            httpasyncclient
            4.1
        
 二、HttpClientサービス情報の設定
# http    
http:
  #      
  maxTotal: 100
  #    
  defaultMaxPerRoute : 20
  #          
  connectTimeout: 1000
  #                
  connectionRequestTimeout: 500
  #          
  socketTimeout: 10000
  #              
  staleConnectionCheckEnabled: true
三、設定情報の読み込み
/**
 * @program: springboot-mybatis-swagger
 * @description: http  
 * @author: Mario
 * @create: 2019-07-15 09:06
 **/
@Configuration
public class HttpClientConfig {
    @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;

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

    /**
     *       ,        。
     *                        
     * @param httpClientConnectionManager
     * @return
     */
    @Bean(name = "httpClientBuilder")
    public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager httpClientConnectionManager){

        //HttpClientBuilder       protected  ,          new      HttpClientBuilder,    HttpClientBuilder       create()   HttpClientBuilder  
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        httpClientBuilder.setConnectionManager(httpClientConnectionManager);

        return httpClientBuilder;
    }

    /**
     *      ,    httpClient
     * @param httpClientBuilder
     * @return
     */
    @Bean
    public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){
        return httpClientBuilder.build();
    }

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

    /**
     *   builder    RequestConfig  
     * @param builder
     * @return
     */
    @Bean
    public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
        return builder.build();
    }
}
四、スレッドのオープンとクローズ 
/**
 * @program: springboot-mybatis-swagger
 * @description: http     
 * @author: Mario
 * @create: 2019-07-15 09:09
 **/
@Component
public class IdleConnectionEvictor extends Thread {
    @Autowired
    private HttpClientConnectionManager connMgr;

    private volatile boolean shutdown;

    public IdleConnectionEvictor() {
        super();
        super.start();
    }

    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    //        
                    connMgr.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            //   
        }
    }

    //           
    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}
五、要求結果パッケージ
/**
 * @program: springboot-mybatis-swagger
 * @description: HTTP    
 * @author: Mario
 * @create: 2019-07-15 09:10
 **/
@Data
public class HttpResultDTO {
    //    
    @NonNull
    private Integer code;

    //    
    @NonNull
    private String body;
}
六、各種要求パッケージ 
Get/Postなどの要求は余分なパラメータをカプセル化している可能性があります。その後は自分で分解します。
@Component
public class HttpAPIController {

    private static CloseableHttpClient httpClient;

    /**
     *   SSL  
     */
    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL)
                    .loadTrustMaterial((x, y) -> true).build();
            /**
             *  、    :connectionTimeout-->       url       
             *  、      :SocketTimeout-->        url,  response       
             */
            RequestConfig config = RequestConfig.custom().setConnectTimeout(500000).setSocketTimeout(500000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext)
                    .setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private RequestConfig config;

    /**
     * @description GET---   
     * @param url
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:02
     */
    /*public HttpResultDTO doGet(String url) throws Exception {
        //    http get   
        HttpGet httpGet = new HttpGet(url);

        //       
        httpGet.setConfig(config);

        //      
        httpGet.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }*/

    /**
     * @description GET---    
     * @param url
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:04
     */
   /* public HttpResultDTO doGetWithHeaders(String url, Map headers) throws Exception {
        //    http get   
        HttpGet httpGet = new HttpGet(url);

        //       
        httpGet.setConfig(config);

        //      
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key).toString();
                httpGet.addHeader(key,value);
            }
        }

        //      
        httpGet.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }*/

    /**
     * @description GET--- Map    
     * @param url
	 * @param mapParams
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:06
     */
    /*public HttpResultDTO doGetWithParams(String url, Map mapParams) throws Exception {
        //   URL
        URIBuilder uriBuilder = new URIBuilder(url);

        if (mapParams != null) {
            //   map,      
            for (Map.Entry entry : mapParams.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        //        get  
        return this.doGet(uriBuilder.build().toString());

    }*/
    
    /**
     * @description GET--- Map         
     * @param url
	 * @param mapParams
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:08
     */
    public HttpResultDTO doGetWithParamsAndHeaders(String url, Map mapParams , Map headers) throws Exception {
        //    http get   
        HttpGet httpGet = new HttpGet(url);

        //       
        httpGet.setConfig(config);

        //      
        httpGet.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
        
        //      
        if (mapParams != null) {
            //   URL
            URIBuilder uriBuilder = new URIBuilder(url);
            //   map,      
            for (Map.Entry entry : mapParams.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
            //      
            url = uriBuilder.build().toString();
        }
        
        //      
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key).toString();
                httpGet.addHeader(key,value);
            }
        }

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }



    /**
     * @description POST--   
     * @param url
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:14
     */
    /*public HttpResultDTO doPost(String url) throws Exception {
        //   httpPost  
        HttpPost httpPost = new HttpPost(url);
        
        //       
        httpPost.setConfig(config);
        
        //     
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }*/

    /**
     * @description POST---  
     * @param url
	 * @param params
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:16
     */
    /*public HttpResultDTO doPostWithParams(String url, Map params) throws Exception {
        //   httpPost  
        HttpPost httpPost = new HttpPost(url);

        //       
        httpPost.setConfig(config);

        //   map    ,        ,  from    
        if (params != null) {
            List list = new ArrayList();
            for (Map.Entry entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            //   from    
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

            //      post 
            httpPost.setEntity(urlEncodedFormEntity);
        }

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }*/

    /**
     * @description POST---    
     * @param url
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:17
     */
    /*public HttpResultDTO doPostWithHeaders(String url, Map headers) throws Exception {
        //   httpPost  
        HttpPost httpPost = new HttpPost(url);

        //       
        httpPost.setConfig(config);

        //      
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key).toString();
                httpPost.addHeader(key,value);
            }
        }

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        //          
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }*/


    /**
     * @description POST---  (    、Map  、   )
     * @param url
	 * @param mapParams
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:22
     */
    public HttpResultDTO doPostWithParamsAndHeaders(String url, Map mapParams , Map headers) throws Exception {
        //   httpPost  
        HttpPost httpPost = new HttpPost(url);
        //       
        httpPost.setConfig(config);

        //   map    ,        ,  from    
        if (mapParams != null) {
            List list = new ArrayList();
            for (Map.Entry entry : mapParams.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            //   from    
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

            //      post 
            httpPost.setEntity(urlEncodedFormEntity);
        }

        //      
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key).toString();
                httpPost.addHeader(key,value);
            }
        }

        //     
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }



    /**
     * @description POST---  (    、JSON   、   )
     * @param url
	 * @param jsonParam
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:20
     */
    public static HttpResultDTO doPostWithJsonParamAndHeaders(String url, String jsonParam, Map headers) throws Exception {
        //   httpPost  
        HttpPost httpPost = new HttpPost(url);

        //      
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key).toString();
                httpPost.addHeader(key, value);
            }
        }

        //    Json      
        StringEntity stringEntity = new StringEntity(jsonParam, "utf-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        //     
        CloseableHttpResponse response = httpClient.execute(httpPost);

        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }

    /**
     * @description PUT---  (    、JSON   、   )
     * @param url
	 * @param jsonParam
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:32
     */
    public static HttpResultDTO doPutWithJsonAndHeaders(String url,String jsonParam,Map headers) throws Exception{
        //   httpPut  
        HttpPut httpPut = new HttpPut(url);

        //  header
        httpPut.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpPut.setHeader(entry.getKey(),entry.getValue());
            }
        }

        //      
        if (StringUtils.isNotEmpty(jsonParam)) {
            StringEntity stringEntity = new StringEntity(jsonParam, "utf-8");
            httpPut.setEntity(stringEntity);
        }
        
        //     
        CloseableHttpResponse response = httpClient.execute(httpPut);

        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }

    /**
     * @description DELETE---  (    、   )
     * @param url
	 * @param headers
     * @return com.mark.dc2.DTO.HttpResultDTO
     * @author Mario
     * @date 2019/7/23 9:37
     */
    public static HttpResultDTO doDeleteWithHeaders(String url,Map headers) throws Exception{
        //   httpDelete  
        HttpDelete httpDelete = new HttpDelete(url);

        //  header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpDelete.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //     
        CloseableHttpResponse response = httpClient.execute(httpDelete);

        return new HttpResultDTO(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));

    }
}