Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

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

Introduction

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

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:org.openhab.action.openwebif.internal.impl.OpenWebIfCommunicator.java

/**
 * Executes the http request and parses the returned stream.
 *///from ww w.  j  a v a 2  s .  co m
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);

        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);

        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }

        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();

        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);

            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

/**
 * /*from  w  w w .  ja  va2 s  . co  m*/
 * @param url
 * @return URLConnection
 * @throws IOException
 * @throws CertificateException 
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 */
private URLConnection getUrlConnection(URL url) throws IOException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, KeyManagementException {
    final URLConnection orgcon = url.openConnection();
    if (orgcon instanceof HttpsURLConnection) {
        HttpsURLConnection con = (HttpsURLConnection) orgcon;
        con.setHostnameVerifier(new SimpleVerifier());
        con.setSSLSocketFactory(getSSLFactory());
    }
    return orgcon;
}

From source file:org.forgerock.maven.plugins.LinkTester.java

private void checkUrl(String path, String docUrl) {
    if (shouldSkipUrl(docUrl)) {
        debug("Skipping " + docUrl + " since it matches a skipUrlPattern");
        return;/*from w  w w.  j a  v  a  2s  .c  om*/
    }
    if (tested.contains(docUrl)) {
        if (failedUrls.containsValue(docUrl)) {
            failedUrls.put(path, docUrl);
        }
        return;
    }
    debug("Checking " + docUrl + " from file: " + path);
    try {
        URL url = new URL(docUrl);
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) urlConn;
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
                httpsConn.setHostnameVerifier(new TrustAllHostnameVerifier());
                httpsConn.setSSLSocketFactory(TRUST_ALL_SOCKET_FACTORY);
            }

            conn.setConnectTimeout(1000);
            //if we don't get anything back within 15 seconds it is safe to assume that something is really wrong
            //with that site..
            conn.setReadTimeout(15000);
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400) {
                warn(docUrl + ": received unexpected response code: " + responseCode);
                failedUrls.put(path, docUrl);
            }
        }
    } catch (SocketTimeoutException ste) {
        warn(docUrl + ": " + ste.getClass().getName() + " " + ste.getMessage());
        timedOutUrls.put(path, docUrl);
    } catch (Exception ex) {
        warn(docUrl + ": " + ex.getClass().getName() + " " + ex.getMessage());
        failedUrls.put(path, docUrl);
    }
    tested.add(docUrl);
}

From source file:io.github.retz.web.Client.java

public int getBinaryFile(int id, String file, OutputStream out) throws IOException {
    String date = TimestampHelper.now();
    String resource = "/job/" + id + "/download?path=" + file;
    AuthHeader header = authenticator.header("GET", "", date, resource);
    URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode!
    LOG.info("Fetching {}", url);
    HttpURLConnection conn;//  www. j a  v  a  2 s .c  o m

    conn = (HttpURLConnection) url.openConnection();
    //LOG.info("classname> {}", conn.getClass().getName());
    if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) {
        if (verboseLog) {
            LOG.warn(
                    "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message.");
        }
        HttpsURLConnection sslCon = (HttpsURLConnection) conn;
        if (socketFactory != null) {
            sslCon.setSSLSocketFactory(socketFactory);
        }
        if (hostnameVerifier != null) {
            sslCon.setHostnameVerifier(hostnameVerifier);
        }
    }
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/octet-stream");
    conn.setRequestProperty("Authorization", header.buildHeader());
    conn.setRequestProperty("Date", date);
    conn.setRequestProperty("Content-md5", "");
    conn.setDoInput(true);
    String s2s = authenticator.string2sign("GET", "", date, resource);
    LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s);

    if (conn.getResponseCode() != 200) {
        if (verboseLog) {
            LOG.warn("HTTP Response:", conn.getResponseMessage());
        }
        if (conn.getResponseCode() < 200) {
            throw new AssertionError(conn.getResponseMessage());
        } else if (conn.getResponseCode() == 404) {
            throw new FileNotFoundException(url.toString());
        } else {
            String message;
            try {
                Response response = MAPPER.readValue(conn.getErrorStream(), Response.class);
                message = response.status();
                LOG.error(message, response);
            } catch (JsonProcessingException e) {
                message = e.toString();
                LOG.error(message, e);
            }
            throw new UnknownError(message);
        }
    }

    int size = conn.getContentLength();
    if (size < 0) {
        throw new IOException("Illegal content length:" + size);
    } else if (size == 0) {
        // not bytes to save;
        return 0;
    }
    try {
        return IOUtils.copy(conn.getInputStream(), out);
    } finally {
        conn.disconnect();
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private HttpsURLConnection openSecureConnection(URL url) throws Exception {

    InputStream keyStream = new FileInputStream(truststorePath);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray());

    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
            Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm));
    trustFactory.init(keystore);//from  w  w w  .ja  v a  2 s  . c  o m

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustFactory.getTrustManagers(), null);

    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

    httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());

    httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    return httpsURLConnection;
}

From source file:org.apache.hadoop.security.ssl.SSLFactory.java

/**
 * If the given {@link HttpURLConnection} is an {@link HttpsURLConnection}
 * configures the connection with the {@link SSLSocketFactory} and
 * {@link HostnameVerifier} of this SSLFactory, otherwise does nothing.
 *
 * @param conn the {@link HttpURLConnection} instance to configure.
 * @return the configured {@link HttpURLConnection} instance.
 *
 * @throws IOException if an IO error occurred.
 *///from  ww  w .j av a 2 s  .c  o  m
@Override
public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection sslConn = (HttpsURLConnection) conn;
        try {
            sslConn.setSSLSocketFactory(createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        sslConn.setHostnameVerifier(getHostnameVerifier());
        conn = sslConn;
    }
    return conn;
}

From source file:org.openintents.lib.DeliciousApiHelper.java

public String[] getTags() throws java.io.IOException {

    String[] result = null;//from   w  w  w. j  a  v a  2 s .  com
    String rpc = mAPI + "tags/get";
    Element tag;
    java.net.URL u = null;

    try {
        u = new URL(rpc);

    } catch (java.net.MalformedURLException mu) {
        System.out.println("Malformed URL>>" + mu.getMessage());
    }

    Document doc = null;

    try {
        javax.net.ssl.HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) u.openConnection();
        //that's actualy pretty ugly to do, but a neede workaround for m5.rc15
        javax.net.ssl.HostnameVerifier v = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();

        connection.setHostnameVerifier(v);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        doc = db.parse(connection.getInputStream());

    } catch (java.io.IOException ioe) {
        System.out.println("Error >>" + ioe.getMessage());
        Log.e(_TAG, "Error >>" + ioe.getMessage());

    } catch (ParserConfigurationException pce) {
        System.out.println("ERror >>" + pce.getMessage());
        Log.e(_TAG, "ERror >>" + pce.getMessage());
    } catch (SAXException se) {
        System.out.println("ERRROR>>" + se.getMessage());
        Log.e(_TAG, "ERRROR>>" + se.getMessage());

    } catch (Exception e) {
        Log.e(_TAG, "Error while excecuting HTTP method. URL is: " + u);
        System.out.println("Error while excecuting HTTP method. URL is: " + u);
        e.printStackTrace();
    }

    if (doc == null) {
        Log.e(_TAG, "document was null, check internet connection?");
        throw new java.io.IOException("Error reading stream >>" + rpc + "<<");

    }
    int tagsLen = doc.getElementsByTagName("tag").getLength();
    result = new String[tagsLen];
    for (int i = 0; i < tagsLen; i++) {
        tag = (Element) doc.getElementsByTagName("tag").item(i);
        result[i] = new String(tag.getAttribute("tag").trim());
    }

    //System.out.println( new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next() );
    return result;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url/*from   ww  w  .  java 2 s  .  co m*/
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

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

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:org.openintents.lib.DeliciousApiHelper.java

public boolean addPost(String itemUrl, String description, String extended, String[] tags, boolean shared)
        throws java.io.IOException {

    String rpc = mAPI + "posts/add?";
    StringBuffer rpcBuf = new StringBuffer();
    StringBuffer tagsBuf = new StringBuffer();
    Element tag;//from   w ww  .j av  a2 s .c o m
    URL u = null;

    String dateStamp;
    //TODO: timestamps

    if (description == null || description.equals("")) {
        description = "no description";
    }
    if (extended == null) {
        extended = new String();
    }

    try {

        rpcBuf.append("&url=" + itemUrl);
        rpcBuf.append("&description=" + URLEncoder.encode(description, "UTF8"));
        rpcBuf.append("&extendend=" + URLEncoder.encode(extended, "UTF8"));
        int tagsLen = tags.length;

        if (mAPI.equals(MAGNOLIA_API)) {
            //Magnolia uses comma as tag separator,..
            for (int i = 0; i < tagsLen; i++) {
                tagsBuf.append(URLEncoder.encode(tags[i]) + ",");
            }
        } else if (mAPI.equals(DELICIOUS_API)) {
            //while Delicious uses spaces
            for (int i = 0; i < tagsLen; i++) {
                tagsBuf.append(URLEncoder.encode(tags[i]) + " ");
            }
        }

        rpcBuf.append("&tags=" + tagsBuf.toString());
        if (shared) {
            rpcBuf.append("&shared=yes");
        } else {
            rpcBuf.append("&shared=no");
        }
        rpcBuf.append("&replace=no");

    } catch (Exception e) {
        Log.e(_TAG, "ERROR Encoding URL Parameters");
        e.printStackTrace();
    }

    rpc += rpcBuf.toString();

    //rpc=rpcBuf.toString();
    System.out.println("\n" + rpc + "\n");
    try {
        u = new URL(rpc);
    } catch (java.net.MalformedURLException mu) {
        System.out.println("Malformed URL>>" + mu.getMessage());
    }

    String s = "";
    try {
        javax.net.ssl.HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) u.openConnection();
        //that's actualy pretty ugly to do, but a neede workaround for m5.rc15
        javax.net.ssl.HostnameVerifier v = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();

        connection.setHostnameVerifier(v);

        //tru3 3v1l h4ack1ng ;)
        s = new Scanner(connection.getInputStream()).useDelimiter("\\Z").next();

    } catch (java.io.IOException ioe) {
        System.out.println("Error >>" + ioe.getMessage());
        Log.e(_TAG, "Error >>" + ioe.getMessage());

    } catch (Exception e) {
        Log.e(_TAG, "Error while excecuting HTTP method. URL is: " + u);
        System.out.println("Error while excecuting HTTP method. URL is: " + u);
        e.printStackTrace();
    }

    if (s.equals("<result code=\"done\" />")) {
        //   System.out.println("YEA!");
        return true;
    }
    //System.out.println(s);

    return false;
}

From source file:org.kontalk.upload.HTPPFileUploadConnection.java

private void setupClient(HttpsURLConnection conn, long length, String mime, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(//from   w  ww . j a  va2s .c o m
            ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Length", String.valueOf(length));
    conn.setRequestMethod("PUT");
}