HttpClient 提示403 - smile0821/learngit GitHub Wiki

https://www.cnblogs.com/lykbk/p/sdfsdfsdf4rte454.html @Component public class ISupRestRequest { private final static Logger log = LoggerFactory.getLogger(ISupRestRequest.class);

private String appId;

private String tokenIntranet;

private CloseableHttpClient httpClient;

public <T> T get(String url, String Data, Class<T> responseType, Environment env, String language,
        String userId)
    throws Exception
{
    RestTemplate resttemplate = new RestTemplate(generateHttpRequestFactory());
    
    appId = env.getProperty("service.appId");
    tokenIntranet = env.getProperty("service.intranet");
    
    List<ClientHttpRequestInterceptor> interceptorList = new ArrayList<ClientHttpRequestInterceptor>();
    interceptorList.add(new ClientHttpRequestInterceptor()
    {
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException
        {
            HttpHeaders headers = request.getHeaders();
            headers.set("language", language);
            if(StringUtils.isNoneEmpty(userId)){
                headers.set("userId", userId);
            }else{
                headers.set("userId", " ");
            }
            String token = getToken();

            headers.set("Authorization", token);
            return execution.execute(request, body);
        }
    });
    resttemplate.setInterceptors(interceptorList);
    
    T result = resttemplate.getForObject(url, responseType, Data);
    // if (null != httpClient)
    // {
    // httpClient.close();
    // }
    return result;
}    


private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws Exception
{
    ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
            .getSocketFactory();
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy()
    {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
        {
            return true;
        }
    }).build();
    // SSLContext sslContext = getSSLContext();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new String[] {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
    // keep alive stategy
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy()
    {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context)
        {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext())
            {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout"))
                {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 60 * 1000;// 如果没有约定,则默认定义时长为60s
        }
    };
    
    Registry<ConnectionSocketFactory> registry = RegistryBuilder
            .<ConnectionSocketFactory> create().register("http", plainsf)
            .register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(500);
    cm.setDefaultMaxPerRoute(50);
    // 请求重试处理
    HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception,
                int executionCount, HttpContext context) {
            if (executionCount >= 10)
            {// 如果已经重试了10次,就放弃
                return false;
            }
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                return false;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                return false;
            }
            if (exception instanceof SSLException) {// SSL握手异常
                return false;
            }

            HttpClientContext clientContext = HttpClientContext
                    .adapt(context);
            HttpRequest request = (HttpRequest)clientContext.getRequest();
            // 如果请求是幂等的,就再次尝试
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setKeepAliveStrategy(
            keepAliveStrategy).setRetryHandler(
            httpRequestRetryHandler).build();
    factory.setHttpClient(httpClient);
    factory.setConnectTimeout(1800000);
    factory.setReadTimeout(1800000);
    return factory;
}