当前位置: 首页>>代码示例>>Java>>正文


Java TrustStrategy类代码示例

本文整理汇总了Java中org.apache.http.ssl.TrustStrategy的典型用法代码示例。如果您正苦于以下问题:Java TrustStrategy类的具体用法?Java TrustStrategy怎么用?Java TrustStrategy使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


TrustStrategy类属于org.apache.http.ssl包,在下文中一共展示了TrustStrategy类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: buildCertificateIgnoringSslContext

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
 * but may be useful in certain testing or development scenarios.
 *
 * @return The SSLContext
 */
public static SSLContext buildCertificateIgnoringSslContext() {
	try {
		return SSLContexts
			.custom()
			.loadTrustMaterial(new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					return true;
				}
			})
			.build();
	}
	catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:23,代码来源:HttpClientUtils.java

示例2: buildHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
/**
 * This creates a HTTP client instance for connecting the IFTTT server.
 * 
 * @return the HTTP client instance
 */
private CloseableHttpClient buildHttpClient ()
{
    if ( configuration.isIftttIgnoreServerCertificate() ) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException
                {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }
        catch (Exception ex) {
            LOG.error(ex);
            // This should never happen, but we have to handle it
            throw new RuntimeException(ex);
        }
    }
    else {
        return HttpClients.createDefault();
    }
}
 
开发者ID:zazaz-de,项目名称:iot-device-bosch-indego-controller,代码行数:31,代码来源:IftttIndegoAdapter.java

示例3: createSSLHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
/**
 * @return
 */
private HttpClient createSSLHttpClient() {

	final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

		@Override
		public boolean isTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException {
			return true;
		}
	};

	SSLContext sslContext = null;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
	} catch (final Exception e) {
		System.out.println("Could not create SSLContext");
	}

	return HttpClientBuilder.create().setSSLContext(sslContext).build();
}
 
开发者ID:kevinsamyn,项目名称:soccerama-pro-client,代码行数:23,代码来源:SocceramaAPIClient.java

示例4: testPost

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
@Test
public void testPost() throws Exception {
	SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
			new TrustStrategy() {
				//信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType)
						throws CertificateException {
					return true;
				}
			}).build();
	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
	CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

	HttpGet request = new HttpGet("https://www.baidu.com");
	request.addHeader(
			"User-Agent",
			"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36");

	final CloseableHttpResponse response = httpClient.execute(request);

	System.out.println(response.getStatusLine().getStatusCode());

	System.out.println(EntityUtils.toString(response.getEntity()));
}
 
开发者ID:5waynewang,项目名称:commons-jkit,代码行数:25,代码来源:SSLHttpClientTest.java

示例5: insecureHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
@Bean("httpClient")
@Profile("insecure")
@SneakyThrows
public HttpClient insecureHttpClient(@Value("${spring.application.name}") String userAgent) {
    // http://stackoverflow.com/a/41618092/1393467
    TrustStrategy trustStrategy = (X509Certificate[] chain, String authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).build();
    return configure(HttpClients.custom(), userAgent)
            .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext))
            .build();
}
 
开发者ID:ePages-de,项目名称:spring-boot-readiness,代码行数:12,代码来源:RestTemplateConfiguration.java

示例6: getHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
/**
 * @see http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
 * @return
 * @throws Exception
 */
public static synchronized HttpClient getHttpClient() throws Exception
{
   HttpClientBuilder b = HttpClientBuilder.create();

   // setup a Trust Strategy that allows all certificates.
   //
   SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
      {
         public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
         {
            return true;
         }
      }).build();
   b.setSslcontext(sslContext);

   // don't check Hostnames, either.
   //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
   HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

   // here's the special part:
   //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
   //      -- and create a Registry, to register it.
   //
   SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
   //Registry<ConnectionSocketFactory> socketFactoryRegistry = ;

   // now, we create connection-manager using our Registry.
   //      -- allows multi-threaded use
   PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build());
   b.setConnectionManager(connMgr);

   // finally, build the HttpClient;
   //      -- done!
   HttpClient client = b.build();

   return client;
}
 
开发者ID:wellsb1,项目名称:fort_w,代码行数:43,代码来源:Web.java

示例7: createHttpClient_AcceptsUntrustedCerts

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
public HttpClient createHttpClient_AcceptsUntrustedCerts() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    HttpClientBuilder b = HttpClientBuilder.create();
 
    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext( sslContext);
 
    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
 
    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();
 
    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
    b.setConnectionManager( connMgr);
 
    // finally, build the HttpClient;
    //      -- done!
    HttpClient client = b.build();
    return client;
}
 
开发者ID:zsavvas,项目名称:ReCRED_FIDO_UAF_OIDC,代码行数:37,代码来源:UserLoader.java

示例8: connect

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
public void connect() {
	MQTT mqtt = new MQTT();
	
	try {
		mqtt.setHost(connectionInfo.getBiobrightUrl());
		mqtt.setUserName(connectionInfo.getBiobrightUserName());
		mqtt.setPassword(connectionInfo.getBiobrightPassword());
		
		// TODO change security policy that is actually disabled with this code.
		TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
		
		SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
		        .loadTrustMaterial(null, acceptingTrustStrategy)
		        .build();
		
		mqtt.setSslContext(sslContext);

		logger.info("Opening MQTT socket.. ");
		connection = mqtt.blockingConnection();
		logger.info("Opened MQTT socket, connecting.. ");
		connection.connect();			
		logger.info("Connected MQTT socket.. ");
	} catch (Exception e) {
		logger.error("connect()", e);
		if(connection != null) {
			connection = null;
		}
		throw new RuntimeException("Connection failed.", e);
	}
}
 
开发者ID:openQCM,项目名称:openQCM2,代码行数:31,代码来源:BiobrightClient.java

示例9: createHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
开发者ID:wso2,项目名称:product-iots,代码行数:39,代码来源:HTTPInvoker.java

示例10: getHttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
private static CloseableHttpClient getHttpClient()
    throws IOException {
  try {
    // Self sign SSL
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // Create client
    return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore()).build();
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    throw new IOException("Issue with creating http client", e);
  }
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:15,代码来源:AzkabanAjaxAPIClient.java

示例11: getConnectionManager

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
public static HttpClientConnectionManager getConnectionManager() {

        // ConnectionSocketFactory plainsf = null;
        LayeredConnectionSocketFactory sslsf = null;

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

        PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        registryBuilder.register("http", plainsf);

        try {

            // Trust own CA and all self-signed certs
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();

            HostnameVerifier allowAllHostnameVerifier = NoopHostnameVerifier.INSTANCE;
            sslsf = new SSLConnectionSocketFactory(sslcontext, allowAllHostnameVerifier);

            registryBuilder.register("https", sslsf);

        } catch (Throwable e) {

            logger.error("https ssl init failed", e);
        }

        Registry<ConnectionSocketFactory> r = registryBuilder.build();

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(r);
        connManager.setMaxTotal(100);// 连接池最大并发连接数
        connManager.setDefaultMaxPerRoute(100);// 单路由最大并发数
        return connManager;

    }
 
开发者ID:jiucai,项目名称:appframework,代码行数:40,代码来源:HttpClientUtil.java

示例12: KF6Service

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
public KF6Service() {
	gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
	// client = HttpClientBuilder.create().build();
	try {
		TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
		SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		client =
                   HttpClients
                           .custom()
                           .setSSLContext(sslContext)
                           .build();
	} catch (Exception ex) {
		throw new RuntimeException(ex);
	}
}
 
开发者ID:macc704,项目名称:KBDeX,代码行数:16,代码来源:KF6Service.java

示例13: getHttpClientWithoutSslVerify

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
private static HttpClient getHttpClientWithoutSslVerify() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            return true;
        }
    });
    final SSLContext sslContext = builder.build();
    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            builder.build());

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("https", socketFactory)
            .build();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, null, null, null, 30, TimeUnit.SECONDS
    );

    connectionManager.setMaxTotal(30);
    connectionManager.setDefaultMaxPerRoute(30);
    return HttpClients
            .custom()
            .setConnectionManager(connectionManager)
            .build();
}
 
开发者ID:iovation,项目名称:launchkey-java,代码行数:29,代码来源:DemoApp.java

示例14: initClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
private void initClient( String accessKey, String secretKey, List<Header> defaultHeadersOverride, int connectionRequestTimeout, int connectionTimeout, int socketTimeout, HttpHost proxy, boolean noSslValidation, String impersonateUsername ) {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    requestConfigBuilder.setConnectionRequestTimeout( connectionRequestTimeout ).setConnectTimeout( connectionTimeout ).setSocketTimeout( socketTimeout );
    if( proxy != null )
        requestConfigBuilder.setProxy( proxy );

    SSLContext sslContext = null;
    // Note: this block of code disables SSL validation. It is only used during development/testing when testing through a proxy
    if( noSslValidation ) {
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {
                    return true;
                }
            } )
                    .build();
        } catch( Exception e ) {
        }
    }

    //system properties
    Map<String, String> systemProperties = ManagementFactory.getRuntimeMXBean().getSystemProperties();

    if ( defaultHeadersOverride == null ) {
        defaultHeaders = new ArrayList<>( 3 );
        defaultHeaders.add( new BasicHeader( "X-ApiKeys", String.format( "accessKey=%s; secretKey=%s", accessKey, secretKey ) ) );
        defaultHeaders.add( new BasicHeader( "User-Agent", String.format( "TenableIOSDK Java/%s %s/%s/%s", systemProperties.get( "java.runtime.version" ), systemProperties.get( "os.name" ), systemProperties.get( "os.version" ), systemProperties.get( "os.arch" ) ) ) );
        defaultHeaders.add( new BasicHeader( "Accept", "*/*" ) );

        if ( impersonateUsername != null ) {
            defaultHeaders.add( new BasicHeader( "X-Impersonate", "username=" + impersonateUsername ) );
        }
    } else {
        defaultHeaders = defaultHeadersOverride;
    }

    asyncClient = HttpAsyncClients.custom()
            .setDefaultRequestConfig( requestConfigBuilder.build() )
            .setDefaultHeaders( defaultHeaders )
            .setSSLContext( sslContext )
            .build();

    asyncClient.start();
}
 
开发者ID:tenable,项目名称:Tenable.io-SDK-for-Java,代码行数:47,代码来源:AsyncHttpService.java

示例15: HttpClient

import org.apache.http.ssl.TrustStrategy; //导入依赖的package包/类
public HttpClient(String proxyUrl, String proxyUser, String proxyPass) {
    HttpClientBuilder builder = HttpClientBuilder.create()
            .setConnectionManagerShared(true);
    try {
        Optional<HttpHost> proxyHost = createProxyHttpHost(proxyUrl);
        if (proxyHost.isPresent()) {
            builder.setProxy(proxyHost.get());
            Optional<BasicCredentialsProvider> credentialsProvider = createBasicCredentialsProvider(
                    proxyUrl, proxyUser, proxyPass, proxyHost.get());
            if (credentialsProvider.isPresent()) {
                builder.setDefaultCredentialsProvider(
                        credentialsProvider.get());
            }
        }

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, allHostsValid);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);

        builder.setConnectionManager(cm);
    } catch (Exception e) {
        throw new WebDriverManagerException(e);
    }

    closeableHttpClient = builder.useSystemProperties().build();
}
 
开发者ID:bonigarcia,项目名称:webdrivermanager,代码行数:45,代码来源:HttpClient.java


注:本文中的org.apache.http.ssl.TrustStrategy类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。