Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

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

Prototype

HostnameVerifier

Source Link

Usage

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

private void process(LogEntry logEntry) {
    if (logEntry.getLevel() <= getLogLevelConfig()) {
        if (!"true".equals(getConfig(LogstashConfig.ENABLED))) {
            return;
        }/*  www . jav  a  2  s.c o m*/
        ;
        for (ILogstashFilter logstashFilter : logstashFilters) {
            if (!logstashFilter.apply(logEntry)) {
                return;
            }
        }
        String request = getConfig(LogstashConfig.URL);
        if (!request.endsWith("/")) {
            request += "/";
        }
        HttpURLConnection conn = null;
        try {
            JSONObject values = serializeLogEntry(logEntry);

            String payload = values.toJSONString();
            byte[] postData = payload.getBytes(StandardCharsets.UTF_8);

            String username = getConfig(LogstashConfig.USERNAME);
            String password = getConfig(LogstashConfig.PASSWORD);

            String authString = username + ":" + password;
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            URL url = new URL(request);

            conn = (HttpURLConnection) url.openConnection();
            if (request.startsWith("https") && "true".equals(getConfig(LogstashConfig.SSL_NO_CHECK))) {
                if (sslSocketFactory != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
                    ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
                }
            }
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setReadTimeout(30 * SECONDS);
            conn.setConnectTimeout(30 * SECONDS);
            if (username != null && !"".equals(username)) {
                conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
            }
            conn.setUseCaches(false);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData);
                wr.flush();
                wr.close();
            }
            if (conn.getResponseCode() != 200) {
                throw new IOException(
                        "Got response " + conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}

From source file:jp.primecloud.auto.sdk.Requester.java

protected HttpURLConnection createConnection(String url, PccOptions options)
        throws IOException, GeneralSecurityException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");

    if (options != null) {
        // HTTPS?
        if (connection instanceof HttpsURLConnection && Boolean.TRUE.equals(options.getIgnoreCerts())) {
            HttpsURLConnection connection2 = (HttpsURLConnection) connection;

            // ?// w  w w . j  ava 2s.co m
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            connection2.setSSLSocketFactory(sslcontext.getSocketFactory());

            // ???
            connection2.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }

    return connection;
}

From source file:odata.service.util.Util.java

private static void disableSSLVerification(HttpsURLConnection connection) {
    connection.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }//from ww w. j a va2 s  .  c o m
    });
}

From source file:net.Downloader.java

public void run() {
    OutputStream os = null;//from w  w  w  .j av  a  2  s  .  com
    InputStream is = null;

    ProgressListener progressListener = new ProgressListener();
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new SSLManager() };

        // Install the all-trusting trust manager
        final SSLContext 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);

        os = new FileOutputStream(fl);
        is = conn.getInputStream();

        CountingStream dcount = new CountingStream(os);
        dcount.setListener(progressListener);

        status = "Downloading";
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);

    } catch (UnknownHostException u) {
        System.err.println("Uknown Host2");
        u.printStackTrace();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            status = "Finished";
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request/*from  w w w  .ja  va 2  s.  c  om*/
 * @param resp servlet response
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    URL url = getURL(req, req.getParameter("uri"));
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(true);
    con.setAllowUserInteraction(false);
    con.setUseCaches(false);

    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    // pass along all appropriate HTTP headers
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = (String) headerNames.nextElement();
        if (!unproxiedHeaders.contains(hname.toLowerCase())) {
            con.addRequestProperty(hname, req.getHeader(hname));
        }
    }
    con.connect();

    // read POST data from incoming request, write to outgoing request
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    // read result headers of POST, write to response
    Map<String, List<String>> headers = con.getHeaderFields();
    for (String key : headers.keySet()) {
        if (key != null) { // TODO: why is this check necessary!
            List<String> header = headers.get(key);
            if (header.size() > 0)
                resp.setHeader(key, header.get(0));
        }
    }

    // read result data of POST, write out to response
    in = new BufferedInputStream(con.getInputStream());
    out = new BufferedOutputStream(resp.getOutputStream());
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    con.disconnect();
}

From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java

/**
 * Sending the request and getting the response
 * @param Uri - request url//  www.  j a  v a2  s  . c o m
 * @param append - append request parameters
 * @throws IOException
 */
private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;
        if (requestParameters != null && requestParameters.length() > 0) {
            if (append) {
                urlStr += "?" + requestParameters;
            } else {
                urlStr += requestParameters;
            }
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

private static HttpCookie getTmCookie(final String url, final String username, final String password,
        final int timeout) throws IOException {
    if (tmCookie != null && !tmCookie.hasExpired()) {
        return tmCookie;
    }//from  w  w w .j a v a2s  .c  om

    final String charset = UTF8_STR;
    final String query = String.format("u=%s&p=%s", URLEncoder.encode(username, charset),
            URLEncoder.encode(password, charset));
    final URLConnection connection = new URL(url).openConnection();

    if (!(connection instanceof HttpsURLConnection)) {
        return null;
    }

    final HttpsURLConnection http = (HttpsURLConnection) connection;

    http.setInstanceFollowRedirects(false);

    http.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });

    http.setRequestMethod("POST");
    http.setAllowUserInteraction(true);

    if (timeout != 0) {
        http.setConnectTimeout(timeout);
        http.setReadTimeout(timeout);
    }

    http.setDoOutput(true); // Triggers POST.
    http.setRequestProperty("Accept-Charset", charset);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    OutputStream output = null;

    try {
        output = http.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOGGER.debug(e, e);
            }
        }
    }

    LOGGER.info("fetching cookie: " + url);
    connection.connect();

    tmCookie = HttpCookie.parse(http.getHeaderField("Set-Cookie")).get(0);
    LOGGER.debug("cookie: " + tmCookie);

    return tmCookie;
}

From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java

private static void setTrustAllSSL() throws IOException {
    try {/*from ww  w.  ja v  a2  s. c o  m*/
        HttpsURLConnection.setDefaultSSLSocketFactory(createTrustAllSSLContext().getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);//from  ww w . j  a v a  2  s.  co m
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:it.cineca.iris.restclient.main.RESTIRClient.java

/**
 * Bybass SSL verify/*  www.j a v  a  2 s  .co  m*/
 * @return
 */
private HostnameVerifier getHostnameVerifier() {
    HostnameVerifier hv = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    return hv;
}