Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier.

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:org.parosproxy.paros.core.proxy.WithBasicInfrastructureIntegrationTest.java

/**
 * Use custom TrustManager that trusts everything.
 * Moreover setup custom ProtocolSocketFactory as done in ZAP.
 * //ww  w .j  a v a 2s  .  c  om
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
protected static void initializeLocalSecurity() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } }, new SecureRandom());

    // this doesn't seem to apply to connections through a proxy
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    // setup a hostname verifier that verifies everything
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new SSLConnector(), 443));
}

From source file:org.openmuc.framework.driver.rest.RestConnection.java

public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException {

    this.timeout = timeout;
    wrapper = new JsonWrapper();
    authString = new String(Base64.encodeBase64(credentials.getBytes()));

    if (!deviceAddress.endsWith("/")) {
        this.deviceAddress = deviceAddress + "/channels/";
    } else {/*from   w  w w.  j  av a  2 s  . c om*/
        this.deviceAddress = deviceAddress + "channels/";
    }

    if (deviceAddress.startsWith("https://")) {
        isHTTPS = true;
    } else {
        isHTTPS = false;
    }

    if (isHTTPS) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        // HttpsURLConnection.setFollowRedirects(false);
    }
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {// www.j  av  a  2  s  .  c o m
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override// w ww .j  av  a  2 s  . com
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
            //
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
            //
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    };
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

/**
 * Called by the SCR to activate the component with its configuration read from CAS
 *
 * @param bundleContext BundleContext of the Bundle that defines this component
 * @param configuration Configuration properties for this component obtained from the ConfigAdmin service
 *//*w  w  w .ja v a2 s  . c o m*/
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    this.bundleContext = bundleContext;

    // the configuration is guaranteed not to be null, because the component definition has the
    // configuration-policy set to require. If set to 'optional' then the configuration may be null

    // to override the default refresh interval one has to add a
    // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
    readConfiguration(configuration);

    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (Exception e) {
        logger.error("Cannot initialize SSL Context!" + e.toString());
        setProperlyConfigured(false);
        return;
    }

    setProperlyConfigured(true);
}

From source file:ezbake.deployer.publishers.SecurityServiceClient.java

protected HttpsURLConnection openUrlConnection(URL endpoint) throws IOException, SSLContextException {

    SSLContext sslContext = EzSSL.getSSLContext(config.getEzConfiguration());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override//  ww w . ja v a  2 s . com
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    return (HttpsURLConnection) endpoint.openConnection();
}

From source file:org.robam.xutils.Utils.OtherUtils.java

/**
 *
 *///from www.  j av  a 2s  . c om
public static void trustAllSSLForHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (trustAllCerts == null) {
        trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
    }
    // Install the all-trusting trust manager
    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Throwable e) {
        LogUtils.e(e.getMessage(), e);
    }
    HttpsURLConnection
            .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.github.ibm.domino.client.BaseClient.java

protected void init(String pathSuffix) throws RuntimeException {

    if (database == null || database.isEmpty()) {
        throw new RuntimeErrorException(new Error("Database parameter not found"));
    }//from ww w  .jav  a 2s  .  c  o m
    if (ignoreHostNameMatching) {
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

    StringBuilder p = new StringBuilder();
    if (pathSuffix != null && !pathSuffix.isEmpty()) {
        p.append("/mail");
        p.append("/").append(database);
    }
    p.append("/api/calendar");
    if (pathSuffix != null && !pathSuffix.isEmpty()) {
        p.append("/").append(pathSuffix);
    }
    setPath(p.toString());

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    //        mapper.configure(SerializationFeature. WRITE_NULL_MAP_VALUES, false);

    mapper.registerModule(new Jackson2HalModule());

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(
            Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
    converter.setObjectMapper(mapper);

    restTemplate = new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));

    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor>singletonList(new BasicAuthorizationInterceptor(username, password));
    restTemplate.setRequestFactory(
            new InterceptingClientHttpRequestFactory(restTemplate.getRequestFactory(), interceptors));

}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Creates a rest client./*w  w  w .jav a 2  s.  c om*/
 * 
 * @param hostname
 *            The host name of the server
 * @param port
 *            The TCP port of the server that should be addressed
 * @param scheme
 *            The used protocol scheme
 * @param versionCode
 *            The version of the app (used for user agent)
 * 
 */
public RestClient(final String hostname, final int port, final String scheme, final int versionCode) {
    final StringBuilder uri = new StringBuilder(scheme);
    uri.append("://");
    uri.append(hostname);
    if (port > 0) {
        uri.append(":");
        uri.append(port);
    }
    mBaseUri = uri.toString();
    mHostName = hostname;

    //TODO Fix SSL problem before exchanging user data
    // workaround for SSL problems, may lower the security level (man-in-the-middle-attack possible)
    // Android does not use the correct SSL certificate for wger.de and throws the exception 
    // javax.net.ssl.SSLException: hostname in certificate didn't match: <wger.de> != <vela.uberspace.de> OR <vela.uberspace.de> OR <uberspace.de> OR <*.vela.uberspace.de>
    // issue is not too serious as no user data is exchanged at the moment
    Log.w(TAG,
            "OpenTraining will accept all SSL-certificates. This issue has to be fixed before exchanging real user data.");
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    ClientConnectionManager mgr = new ThreadSafeClientConnManager(client.getParams(), registry);
    mClient = new DefaultHttpClient(mgr, client.getParams());

    mClient.setRedirectHandler(sRedirectHandler);
    mClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);

    // Set verifier     
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    // set user agent
    USER_AGENT = "opentraining/" + versionCode;
}

From source file:info.semanticsoftware.semassist.android.intents.ServiceIntent.java

public String execute() {
    Log.d(Constants.TAG, "factory execute for " + pipelineName + " on server " + candidServerURL + " params "
            + RTParams + " input " + inputString);
    if (candidServerURL.indexOf("https") < 0) {
        Log.d(Constants.TAG, "non secure post to " + candidServerURL);
        RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                RTParams, inputString);//from   w  ww.  j av a  2  s. co m
        Representation representation = new StringRepresentation(request.getXML(), MediaType.APPLICATION_XML);
        Representation response = new ClientResource(candidServerURL).post(representation);
        String responseString = "";
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            responseString = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(Constants.TAG, "$$$ " + responseString);
        return responseString;
    } else {
        try {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = SemAssistApp.getInstance().getContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, SemAssistApp.getInstance().getContext().getString(R.string.keystorePassword)
                        .toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                    RTParams, inputString);
            Representation representation = new StringRepresentation(request.getXML(),
                    MediaType.APPLICATION_XML);

            HttpPost post = new HttpPost(candidServerURL);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            String responseString = "";
            while ((string = bufferedreader.readLine()) != null) {
                responseString += string;
            }
            return responseString;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } //else
    return null;
}