Java 类org.apache.http.conn.ssl.NoopHostnameVerifier 实例源码

项目:Burp-Hunter    文件:HunterRequest.java   
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {

        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
项目:spring-cloud-skipper    文件:AboutController.java   
private String getChecksum(String defaultValue, String url,
        String version) {
    String result = defaultValue;
    if (result == null && StringUtils.hasText(url)) {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        url = constructUrl(url, version);
        try {
            ResponseEntity<String> response
                    = new RestTemplate(requestFactory).exchange(
                    url, HttpMethod.GET, null, String.class);
            if (response.getStatusCode().equals(HttpStatus.OK)) {
                result = response.getBody();
            }
        }
        catch (HttpClientErrorException httpException) {
            // no action necessary set result to undefined
            logger.debug("Didn't retrieve checksum because", httpException);
        }
    }
    return result;
}
项目:websocket-poc    文件:App.java   
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .build();

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}
项目:mxhsd    文件:HttpFederationClient.java   
public HttpFederationClient(HomeserverState global, FederationDomainResolver resolver) {
    this.global = global;
    this.resolver = resolver;

    try {
        SocketConfig sockConf = SocketConfig.custom().setSoTimeout(30000).build();
        // FIXME properly handle SSL context by validating certificate hostname
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        this.client = HttpClientBuilder.create()
                .disableAuthCaching()
                .disableAutomaticRetries()
                .disableCookieManagement()
                .disableRedirectHandling()
                .setDefaultSocketConfig(sockConf)
                .setSSLSocketFactory(sslSocketFactory)
                .setUserAgent(global.getAppName() + "/" + global.getAppVersion())
                .build();
    } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}
项目:rubenlagus-TelegramBots    文件:DefaultAbsSender.java   
protected DefaultAbsSender(DefaultBotOptions options) {
    super();
    this.exe = Executors.newFixedThreadPool(options.getMaxThreads());
    this.options = options;
    httpclient = HttpClientBuilder.create()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setConnectionTimeToLive(70, TimeUnit.SECONDS)
            .setMaxConnTotal(100)
            .build();

    requestConfig = options.getRequestConfig();

    if (requestConfig == null) {
        requestConfig = RequestConfig.copy(RequestConfig.custom().build())
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
    }
}
项目:rubenlagus-TelegramBots    文件:DefaultBotSession.java   
@Override
public synchronized void start() {
    httpclient = HttpClientBuilder.create()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setConnectionTimeToLive(70, TimeUnit.SECONDS)
            .setMaxConnTotal(100)
            .build();
    requestConfig = options.getRequestConfig();
    exponentialBackOff = options.getExponentialBackOff();

    if (exponentialBackOff == null) {
        exponentialBackOff = new ExponentialBackOff();
    }

    if (requestConfig == null) {
        requestConfig = RequestConfig.copy(RequestConfig.custom().build())
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
    }

    super.start();
}
项目:Cognizant-Intelligent-Test-Scripter    文件:AbstractHttpClient.java   
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
项目:calcite-avatica    文件:AvaticaCommonsHttpClientImpl.java   
/**
 * Creates the {@code HostnameVerifier} given the provided {@code verification}.
 *
 * @param verification The intended hostname verification action.
 * @return A verifier for the request verification.
 * @throws IllegalArgumentException if the provided verification cannot be handled.
 */
HostnameVerifier getHostnameVerifier(HostnameVerification verification) {
  // Normally, the configuration logic would give us a default of STRICT if it was not
  // provided by the user. It's easy for us to do a double-check.
  if (verification == null) {
    verification = HostnameVerification.STRICT;
  }
  switch (verification) {
  case STRICT:
    return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
  case NONE:
    return NoopHostnameVerifier.INSTANCE;
  default:
    throw new IllegalArgumentException("Unhandled HostnameVerification: "
        + hostnameVerification);
  }
}
项目:calcite-avatica    文件:AvaticaCommonsHttpClientImplTest.java   
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
项目:telegram-bot_misebot    文件:AbsSender.java   
private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException {
    String responseContent;
    try {
        CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        String url = getBaseUrl() + method.getPath();
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("charset", StandardCharsets.UTF_8.name());
        httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
        CloseableHttpResponse response = httpclient.execute(httppost);
        HttpEntity ht = response.getEntity();
        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new TelegramApiException("Unable to execute " + method.getPath() + " method", e);
    }

    JSONObject jsonObject = new JSONObject(responseContent);
    if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
        throw new TelegramApiException("Error at " + method.getPath(), jsonObject.getString("description"));
    }

    return method.deserializeResponse(jsonObject);
}
项目:infiniboard    文件:UrlSourceJob.java   
CloseableHttpClient configureHttpClient(boolean enableSslVerify) {

    HttpClientBuilder builder = HttpClientBuilder.create();

    if (enableSslVerify) {
      return builder.build();
    }

    SSLContext sslContext = null;
    try {
      sslContext =
          new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
      LOG.error("Could not create ssl context", e);
    }

    builder.setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(sslContext);

    return builder.build();
  }
项目:base    文件:RestServiceImpl.java   
private CloseableHttpClient getHttpsClient()
{
    try
    {
        RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build();

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true );
        SSLConnectionSocketFactory sslSocketFactory =
                new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE );

        return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory )
                          .build();
    }
    catch ( Exception e )
    {
        LOGGER.error( e.getMessage() );
    }

    return HttpClients.createDefault();
}
项目:rundeck-device42-nodes-plugin    文件:AbstractAsynchronousRestClient.java   
/**
 * Create the HTTP clean with basic authentication mechanism using specified
 * credentials
 * 
 * @param username
 *            Authentication username
 * @param password
 *            Authentication password
 * @return
 */
protected static CloseableHttpClient createHttpClient(String username, String password) {
    SSLContext sslContext = createSslContext();
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    List<Header> headers = Arrays.asList(header);

    return HttpClients.custom()
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .setSSLSocketFactory(sslSocketFactory)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultHeaders(headers)
            .build();
}
项目:loginsight-java-api    文件:AsyncLogInsightConnectionStrategy.java   
/**
 * Initializes and returns the httpClient with NoopHostnameVerifier
 * 
 * @return CloseableHttpAsyncClient
 */
@Override
public CloseableHttpAsyncClient getHttpClient() {
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = NonValidatingSSLSocketFactory.getSSLContext();
    // Allow TLSv1 protocol only

    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null,
            new NoopHostnameVerifier());
    List<Header> headers = LogInsightClient.getDefaultHeaders();

    asyncHttpClient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).setDefaultHeaders(headers)
            .build();
    asyncHttpClient.start();

    return asyncHttpClient;
}
项目:hybris-commerce-eclipse-plugin    文件:AbstractHACCommunicationManager.java   
/**
 * Creates {@link HttpClient} that trusts any SSL certificate
 *
 * @return prepared HTTP client
 */
protected HttpClient getSSLAcceptingClient() {
    final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true;
    try {
        final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build();

        sslContext.init(null, getTrustManager(), new SecureRandom());
        final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());

        return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) {
        ConsoleUtils.printError(error.getMessage());
        throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error);
    }
}
项目:jenkinsfile-maven-plugin    文件:ValidateJenkinsfileMojo.java   
/**
 * Allow SSL connections to utilize untrusted certificates
 * 
 * @param httpClientBuilder
 * @throws MojoExecutionException
 */
private void configureInsecureSSL(HttpClientBuilder httpClientBuilder) throws MojoExecutionException {
    try {
        SSLContextBuilder sslBuilder = new SSLContextBuilder();

        // Accept all Certificates
        sslBuilder.loadTrustMaterial(null, AcceptAllTrustStrategy.INSTANCE);

        SSLContext sslContext = sslBuilder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);
        httpClientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        throw new MojoExecutionException("Error setting insecure SSL configuration", e);
    }
}
项目:cerberus-lifecycle-cli    文件:VaultAdminClientFactory.java   
public VaultAdminClient getClient(final String vaultRootToken, final String hostname) {
    final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .cipherSuites(
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
            .build();

    final OkHttpClient httpClient = new OkHttpClient.Builder()
            .hostnameVerifier(new NoopHostnameVerifier())
            .connectionSpecs(Lists.newArrayList(spec))
            .proxy(proxy)
            .connectTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
            .writeTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
            .readTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
            .build();

    return new VaultAdminClient(
            new StaticVaultUrlResolver(toVaultUrl(hostname)),
            new RootCredentialsProvider(vaultRootToken),
            httpClient);
}
项目:cerberus-lifecycle-cli    文件:RestoreCompleteCerberusDataFromS3BackupOperationUserAcceptanceTest.java   
@Test public void
run_restore_complete() throws IOException {
    when(consoleService.readLine(anyString())).thenReturn("proceed");

    CerberusAdminClient adminClient = new CerberusAdminClient(
            new StaticVaultUrlResolver("http://127.0.0.1:8200"),
            new VaultAdminClientFactory.RootCredentialsProvider(rootToken),
            new OkHttpClient.Builder()
                    .hostnameVerifier(new NoopHostnameVerifier())
                    .connectTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
                    .writeTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
                    .readTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT)
                    .build(),
            CerberusModule.configObjectMapper()
    );

    when(vaultAdminClientFactory.createCerberusAdminClient(anyString())).thenReturn(adminClient);

    operation.run(command);
}
项目:TranskribusSwtGui    文件:OAuthGuiUtil.java   
public static void revokeOAuthToken(final String refreshToken, final OAuthProvider prov) throws IOException{

    final String uriStr;
    switch (prov) {
    case Google:
        uriStr = "https://accounts.google.com/o/oauth2/revoke?token=";
        break;
    default:
        throw new IOException("Unknown OAuth Provider: " + prov);
    }

    CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();       
    HttpGet get = new HttpGet(uriStr + refreshToken);
    HttpResponse response = client.execute(get);
    final int status = response.getStatusLine().getStatusCode();        
    if (status != 200) {
        String reason = response.getStatusLine().getReasonPhrase();
        logger.error(reason);
        throw new ClientErrorException(reason, status);
    }
}
项目:TelegramBots    文件:DefaultAbsSender.java   
protected DefaultAbsSender(DefaultBotOptions options) {
    super();
    this.exe = Executors.newFixedThreadPool(options.getMaxThreads());
    this.options = options;
    httpclient = HttpClientBuilder.create()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setConnectionTimeToLive(70, TimeUnit.SECONDS)
            .setMaxConnTotal(100)
            .build();

    requestConfig = options.getRequestConfig();

    if (requestConfig == null) {
        requestConfig = RequestConfig.copy(RequestConfig.custom().build())
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
    }
}
项目:TelegramBots    文件:DefaultBotSession.java   
@Override
public synchronized void start() {
    httpclient = HttpClientBuilder.create()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setConnectionTimeToLive(70, TimeUnit.SECONDS)
            .setMaxConnTotal(100)
            .build();
    requestConfig = options.getRequestConfig();
    exponentialBackOff = options.getExponentialBackOff();

    if (exponentialBackOff == null) {
        exponentialBackOff = new ExponentialBackOff();
    }

    if (requestConfig == null) {
        requestConfig = RequestConfig.copy(RequestConfig.custom().build())
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
    }

    super.start();
}
项目:spring-cloud-dataflow    文件:AboutController.java   
private String getChecksum(String defaultValue, String url,
        String version) {
    String result = defaultValue;
    if (result == null && StringUtils.hasText(url)) {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        url = constructUrl(url, version);
        try {
            ResponseEntity<String> response
                    = new RestTemplate(requestFactory).exchange(
                    url, HttpMethod.GET, null, String.class);
            if (response.getStatusCode().equals(HttpStatus.OK)) {
                result = response.getBody();
            }
        }
        catch (HttpClientErrorException httpException) {
            // no action necessary set result to undefined
            logger.debug("Didn't retrieve checksum because", httpException);
        }
    }
    return result;
}
项目:Tank    文件:TankHttpClient4.java   
/**
 * no-arg constructor for client
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000)
            .setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true)
            .setAuthenticationEnabled(true)
            .setRedirectsEnabled(true)
            .setCookieSpec(CookieSpecs.STANDARD)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}
项目:routing-bird    文件:HttpRequestHelperUtils.java   
public static HttpClient buildHttpClient(boolean sslEnable,
    boolean allowSelfSigendCerts,
    OAuthSigner signer,
    String host,
    int port,
    int socketTimeoutInMillis) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    List<HttpClientConfiguration> configs = new ArrayList<>();
    HttpClientConfig httpClientConfig = HttpClientConfig.newBuilder().setSocketTimeoutInMillis(socketTimeoutInMillis).build();
    configs.add(httpClientConfig);
    if (sslEnable) {

        HttpClientSSLConfig.Builder builder = HttpClientSSLConfig.newBuilder();
        builder.setUseSSL(true);
        if (allowSelfSigendCerts) {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            // Allow TLSv1 protocol only, use NoopHostnameVerifier to trust self-singed cert
            builder.setUseSslWithCustomSSLSocketFactory(new SSLConnectionSocketFactory(sslcontext,
                new String[] { "TLSv1" }, null, new NoopHostnameVerifier()));
        }
        configs.add(builder.build());
    }

    HttpClientFactory httpClientFactory = new HttpClientFactoryProvider().createHttpClientFactory(configs, false);
    return httpClientFactory.createClient(signer, host, port);
}
项目:sonarqube-companion    文件:RestTemplateConfiguration.java   
private RestTemplate getRestTemplateAllowingSelfSigned() {
    try {
        final SSLContext allowSelfSignedSslContext = SSLContexts
                .custom()
                .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .build();
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                allowSelfSignedSslContext,
                NoopHostnameVerifier.INSTANCE
        );
        final CloseableHttpClient httpClient = HttpClientBuilder
                .create()
                .setSSLSocketFactory(sslsf)
                .build();
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    } catch (final Exception exception) {
        throw new SQCompanionException("Can't initialize RestTemplate with Self Signed https support", exception);
    }
}
项目:rundeck-http-plugin    文件:HttpWorkflowStepPlugin.java   
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException {
    SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(true).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) {
        log.debug("Disabling all SSL certificate verification.");
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });

        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
        httpClientBuilder.setSSLContext(sslContextBuilder.build());
    }

    return httpClientBuilder.build();
}
项目:TelegramBotsExample    文件:TransifexService.java   
private String getFileAndroid(String query) {
    String result = null;
    try {
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(BASEURLAndroid.replace("@language", query));
        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String line;
        String responseString = "";
        while ((line = rd.readLine()) != null) {
            responseString += line;
        }

        if (response.getStatusLine().getStatusCode() == STATUS200) {
            result = responseString;
        }
    } catch (IOException e) {
        BotLogger.error(LOGTAG, e);
    }
    return result;
}
项目:JavaMediawikiBot    文件:NetworkingBase.java   
private void setupSSLclient() {
    // Handle SSL
    SSLContext sslcontext = null;
    SSLConnectionSocketFactory factory = null;


        try {
            sslcontext = SSLContexts.custom().useProtocol("SSL").build();
            sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
            factory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            logError("Could not create SSL context. Entering fail state.");
            throw new Error(e.getMessage());
        }



    // Create client and context for web stuff.
    httpclient = HttpClientBuilder.create().setSSLSocketFactory(factory).build();
}
项目:navigator-sdk    文件:SSLUtilsTest.java   
@Test
public void testGetHostnameVerifier() {
  // Default
  HostnameVerifier verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof DefaultHostnameVerifier);

  // Override
  config.setOverrideHostnameVerifier(new TestHostnameVerifier());
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof TestHostnameVerifier);

  // Disabled
  config.setDisableSSLValidation(true);
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof NoopHostnameVerifier);
}
项目:curly    文件:AuthHandler.java   
public CloseableHttpClient getAuthenticatedClient() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build(), NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setDefaultCredentialsProvider(getCredentialsProvider())
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
项目:check-in    文件:SmzdmAndroidTask.java   
@Scheduled(cron = "0 0 5,18 * * ?")
public void run() {
    for (Account account : getAccounts()) {
        try {
            CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
            Executor executor = Executor.newInstance(client).use(new BasicCookieStore());
            String token = login(executor, account);
            if(StringUtils.isNotEmpty(token)) {
                if(checkIn(executor, account, token)) {
                    // lottery(executor, account, token);
                }
            }
        } catch (Exception e) {
            log.error("【SMZDM】【" + account.getUsername() + "】签到异常", e);
        }
    }
}
项目:ds3_java_sdk    文件:NetworkClientImpl.java   
private static CloseableHttpClient createInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    final SSLContext sslContext = new SSLContextBuilder()
            .useProtocol(INSECURE_SSL_PROTOCOL)
            .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslsf)
            .build();
    final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry);

    return HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setSSLSocketFactory(
            sslsf).build();
}
项目:wildfly-core    文件:HttpManagementInterface.java   
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault();
                SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                    new UsernamePasswordCredentials(username, password));

    return HttpClientBuilder.create()
                    .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                    .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                    .setDefaultCredentialsProvider(credentialsProvider)
                    .build();
}
项目:wildfly-core    文件:HttpGenericOperationUnitTestCase.java   
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:citrus-simulator    文件:HttpClientConfig.java   
@Bean
public CloseableHttpClient httpClient() {
    try {
        //new ClassPathResource("").getURL()
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(keyStore, keyPassword.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}
项目:red5-server-common    文件:HttpConnectionUtil.java   
/**
 * Returns a client with all our selected properties / params and SSL enabled.
 * 
 * @return client
 */
public static final HttpClient getSecureClient() {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the ssl verifier to accept all
    client.setSSLHostnameVerifier(new NoopHostnameVerifier());
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    return client.build();
}
项目:pinot    文件:AutoOnboardPinotMetricsUtils.java   
public AutoOnboardPinotMetricsUtils(DataSourceConfig dataSourceConfig)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
  PinotThirdEyeDataSourceConfig pinotThirdeyeDataSourceConfig =
      PinotThirdEyeDataSourceConfig.createFromDataSourceConfig(dataSourceConfig);

  String controllerConnectionScheme = pinotThirdeyeDataSourceConfig.getControllerConnectionScheme();
  if (PinotThirdEyeDataSourceConfig.HTTPS_SCHEME.equals(controllerConnectionScheme)) {
    try {
      // Accept all SSL certificate because we assume that the Pinot broker are setup in the same internal network
      SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new AcceptAllTrustStrategy()).build();
      this.pinotControllerClient =
          HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
      // This section shouldn't happen because we use Accept All Strategy
      LOG.error("Failed to start auto onboard for Pinot data source.");
      throw e;
    }
  } else {
    this.pinotControllerClient = HttpClients.createDefault();
  }

  this.pinotControllerHost = new HttpHost(pinotThirdeyeDataSourceConfig.getControllerHost(),
      pinotThirdeyeDataSourceConfig.getControllerPort(), controllerConnectionScheme);
}
项目:jooby    文件:Client.java   
private Executor executor() {
  if (executor == null) {
    if (this.host.startsWith("https://")) {
      try {
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, (chain, authType) -> true)
            .build();
        builder.setSSLContext(sslContext);
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
      } catch (Exception ex) {
        Throwables.propagate(ex);
      }
    }
    client = builder.build();
    executor = Executor.newInstance(client);
    if (creds != null) {
      executor.auth(creds);
    }
  }
  return executor;
}
项目:commafeed    文件:HttpGetter.java   
public static CloseableHttpClient newClient(int timeout) {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();
    builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING);
    builder.disableAutomaticRetries();

    builder.setSSLContext(SSL_CONTEXT);
    builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

    RequestConfig.Builder configBuilder = RequestConfig.custom();
    configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
    configBuilder.setSocketTimeout(timeout);
    configBuilder.setConnectTimeout(timeout);
    configBuilder.setConnectionRequestTimeout(timeout);
    builder.setDefaultRequestConfig(configBuilder.build());

    builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build());

    return builder.build();
}
项目:spring-cloud-skipper    文件:HttpClientConfigurer.java   
/**
 * Sets the client's {@link javax.net.ssl.SSLContext} to use
 * {@link HttpUtils#buildCertificateIgnoringSslContext()}.
 *
 * @return a reference to {@code this} to enable chained method invocation
 */
public HttpClientConfigurer skipTlsCertificateVerification() {
    httpClientBuilder.setSSLContext(HttpUtils.buildCertificateIgnoringSslContext());
    httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());

    return this;
}