zoukankan      html  css  js  c++  java
  • 七、创建UcRESTTemplate请求管理器

    一、创建UcRESTTemplate管理器封装

    import com.alibaba.fastjson.JSON;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.client.ClientHttpRequestFactory;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    import org.springframework.web.client.HttpStatusCodeException;
    import org.springframework.web.client.RestTemplate;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.security.cert.X509Certificate;
    import java.util.Map;
    所需导入的包
    public class UcRESTTemplate {
    
        private static final int default_connectionTimeout = 30 * 1000;
        private static final int default_socketTimeout = 30 * 1000;
        private int connectionTimeout = 30 * 1000;
        private int socketTimeout = 30 * 1000;
        private int minsTimeoutTime = 1000;
    
        private static final Logger logger = LoggerFactory.getLogger(UcRESTTemplate.class);
    
        public UcRESTTemplate() {
            this.connectionTimeout = UcRESTTemplate.default_connectionTimeout;
            this.socketTimeout = UcRESTTemplate.default_socketTimeout;
        }
    
        public UcRESTTemplate(int connectionTimeout, int socketTimeout) {
            this.connectionTimeout = connectionTimeout < this.minsTimeoutTime ? UcRESTTemplate.default_connectionTimeout
                    : connectionTimeout;
            this.socketTimeout = socketTimeout < this.minsTimeoutTime ? UcRESTTemplate.default_socketTimeout
                    : socketTimeout;
        }
    
        private CloseableHttpClient buildHttpClient() {
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectionTimeout)
            .setSocketTimeout(this.socketTimeout).build();
            HttpClientBuilder cb = HttpClients
                    .custom()
                    .disableAutomaticRetries()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .setDefaultRequestConfig(requestConfig);
    
            try {
                // set ssl context
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(null, new TrustManager[] { new X509TrustManager() {
    
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
    
                    @Override
                    public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
                    }
    
                    @Override
                    public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
                    }
                } }, null);
    
                cb.setSslcontext(ctx);
            } catch (GeneralSecurityException ex) {
                throw new RuntimeException(ex);
            }
            return cb.build();
        }
    
        private static RestTemplate buildTemplate(CloseableHttpClient client) {
            ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                    client);
            return new RestTemplate(requestFactory);
        }
    
        /**
         * @param request
         * @param url
         * @param params maybe null
         * @return
         */
        public ResponseEntity<String> getEntity(String url, HttpEntity<?> request, Map<String, ?> params) {
            if (null == params){
                return getEntity(url, request, String.class);
            }else {
                try {
                    try (CloseableHttpClient client = this.buildHttpClient();) {
                        return UcRESTTemplate.buildTemplate(client).exchange(url, HttpMethod.GET, request, String.class, params);
                    } catch (HttpStatusCodeException ex) {
                        this.handleServerException(url, ex);
                        return null;
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        
        public ResponseEntity<String> getEntity(String url, HttpEntity<?> request) {
            return getEntity(url, request, String.class);
        }
        
        public <T> ResponseEntity<T> getEntity(String url, HttpEntity<?> request, Class<T> responseType) {
            try {
                try (CloseableHttpClient client = this.buildHttpClient();) {
                    return UcRESTTemplate.buildTemplate(client).exchange(url, HttpMethod.GET, request, responseType);
                } catch (HttpStatusCodeException ex) {
                    this.handleServerException(url, ex);
                    return null;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    
        public ResponseEntity<String> postEntity(String url, HttpEntity<?> request) {
            try {
                try (CloseableHttpClient client = this.buildHttpClient();) {
                    return UcRESTTemplate.buildTemplate(client).postForEntity(url, request,
                            String.class);
                } catch (HttpStatusCodeException ex) {
                    return this.handleServerException(url, ex);
                }
            } catch (IOException e) {
                UcRESTTemplate.logger.error("exception is " + e);
                throw new RuntimeException(e);
            }
        }
    
        protected ResponseEntity<String> handleServerException(String url,
                HttpStatusCodeException ex) {
            HttpStatus statusCode = ex.getStatusCode();
            String respString = ex.getResponseBodyAsString();
            logger.error("url:" + url+",statusCode:"+statusCode, ex);
            switch (statusCode) {
            case CONFLICT:
                return new ResponseEntity<>(respString, statusCode);
            case NOT_FOUND:
                throw new RuntimeException("URL not found: " + url);
            default:
                logger.error("Response string:
    " + respString);
                @SuppressWarnings("unchecked")
                Map<String, Object> map = (Map<String, Object>) JSON.parse(respString);
                if (map.containsKey("stackTrace")) {
                    Exception ori = JSON.parseObject(respString, Exception.class);
                    throw new RuntimeException("Exception thrown from server", ori);
                } else {
                    throw new RuntimeException(respString);
                }
            }
        }
    
        /**
         * 发送get请求,获取返回结果
         * 
         * @param <T>
         * @param url
         * @param cls
         * @return
         */
        public <T> T sendHttpsGet(String url, Class<T> cls) {
            CloseableHttpClient client = this.buildHttpClient();
            return buildTemplate(client).getForObject(url, cls);
        }
    
    }
  • 相关阅读:
    Struts2 与 Spring MVC
    RESTful Web Service
    [找程序员代写推荐]spring Scurity终于测试OK了,复杂的功能还待深入研究!发布出来一起探讨吧!
    [找程序员代写推荐]1、拖地要30分钟, 只有一个拖把 2、擦窗要30分钟, 只有一块抹布 3、切菜要30分钟, 只有一把刀 假设只有以上工具才能完成工作时,完成此三件 工作需要两个人工作多长时间?
    [原]精简高效CSS系列之二——浮动float
    [找程序员代写推荐]struts2验证+拦截器+国际化+下载excle文档+struts2二级联动+OGNL表达试+ssh集成部分代码, 项目下载、
    [原]精简高效CSS系列之一——CSS样式用法
    [原]反对网抄,没有规则可以创建目标&quot;install&quot; 靠谱解答
    如何鉴别程序抄袭c语言程序代写
    [原]CSS+DIV总结
  • 原文地址:https://www.cnblogs.com/chushujin/p/11381643.html
Copyright © 2011-2022 走看看