Search in sources :

Example 6 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project cas by apereo.

the class ValidateCaptchaAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
    final String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
    if (StringUtils.isBlank(gRecaptchaResponse)) {
        LOGGER.warn("Recaptcha response is missing from the request");
        return getError(requestContext);
    }
    try {
        final URL obj = new URL(recaptchaProperties.getVerifyUrl());
        final HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", WebUtils.getHttpServletRequestUserAgent());
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        final String postParams = "secret=" + recaptchaProperties.getSecret() + "&response=" + gRecaptchaResponse;
        LOGGER.debug("Sending 'POST' request to URL: [{}]", obj);
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(postParams);
            wr.flush();
        }
        final int responseCode = con.getResponseCode();
        LOGGER.debug("Response Code: [{}]", responseCode);
        if (responseCode == HttpStatus.OK.value()) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                final String response = in.lines().collect(Collectors.joining());
                LOGGER.debug("Google captcha response received: [{}]", response);
                final JsonNode node = READER.readTree(response);
                if (node.has("success") && node.get("success").booleanValue()) {
                    return null;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return getError(requestContext);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) BufferedReader(java.io.BufferedReader) JsonNode(com.fasterxml.jackson.databind.JsonNode) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 7 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project UltimateAndroid by cymcsg.

the class HttpsUtils method sendWithSSlSocket.

/**
     * @deprecated
     */
public static void sendWithSSlSocket(String urlLink) {
    SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    URL url = null;
    try {
        url = new URL(urlLink);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        InputStream inputstream = conn.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
        String string = null;
        while ((string = bufferedreader.readLine()) != null) {
            System.out.println("Received " + string);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
    }
}
Also used : SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 8 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project dropwizard by dropwizard.

the class SslReloadAppTest method certBytes.

/** Issues a POST against the reload ssl admin task, asserts that the code and content
     *  are as expected, and finally returns the server certificate */
private byte[] certBytes(int code, String content) throws Exception {
    final URL url = new URL("https://localhost:" + rule.getAdminPort() + "/tasks/reload-ssl");
    final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    try {
        postIt(conn);
        assertThat(conn.getResponseCode()).isEqualTo(code);
        if (code == 200) {
            assertThat(CharStreams.toString(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))).isEqualTo(content);
        } else {
            assertThat(CharStreams.toString(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))).contains(content);
        }
        // Thus, we return the one and only certificate.
        return conn.getServerCertificates()[0].getEncoded();
    } finally {
        conn.disconnect();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 9 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project AndroidNetworkDemo by dodocat.

the class SelfSignSslOkHttpStack method createConnection.

@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
    if ("https".equals(url.getProtocol()) && socketFactoryMap.containsKey(url.getHost())) {
        HttpsURLConnection connection = (HttpsURLConnection) new OkUrlFactory(okHttpClient).open(url);
        connection.setSSLSocketFactory(socketFactoryMap.get(url.getHost()));
        return connection;
    } else {
        return new OkUrlFactory(okHttpClient).open(url);
    }
}
Also used : OkUrlFactory(com.squareup.okhttp.OkUrlFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 10 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project buck by facebook.

the class HttpDownloader method fetch.

@Override
public boolean fetch(BuckEventBus eventBus, URI uri, Optional<PasswordAuthentication> authentication, Path output) throws IOException {
    if (!("https".equals(uri.getScheme()) || "http".equals(uri.getScheme()))) {
        return false;
    }
    DownloadEvent.Started started = DownloadEvent.started(uri);
    eventBus.post(started);
    try {
        HttpURLConnection connection = createConnection(uri);
        if (authentication.isPresent()) {
            if ("https".equals(uri.getScheme()) && connection instanceof HttpsURLConnection) {
                PasswordAuthentication p = authentication.get();
                String authStr = p.getUserName() + ":" + new String(p.getPassword());
                String authEncoded = BaseEncoding.base64().encode(authStr.getBytes(StandardCharsets.UTF_8));
                connection.addRequestProperty("Authorization", "Basic " + authEncoded);
            } else {
                LOG.info("Refusing to send basic authentication over plain http.");
                return false;
            }
        }
        if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
            LOG.info("Unable to download %s: %s", uri, connection.getResponseMessage());
            return false;
        }
        long contentLength = connection.getContentLengthLong();
        try (InputStream is = new BufferedInputStream(connection.getInputStream());
            OutputStream os = new BufferedOutputStream(Files.newOutputStream(output))) {
            long read = 0;
            while (true) {
                int r = is.read();
                read++;
                if (r == -1) {
                    break;
                }
                if (read % PROGRESS_REPORT_EVERY_N_BYTES == 0) {
                    eventBus.post(new DownloadProgressEvent(uri, contentLength, read));
                }
                os.write(r);
            }
        }
        return true;
    } finally {
        eventBus.post(DownloadEvent.finished(started));
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) BufferedOutputStream(java.io.BufferedOutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)209 URL (java.net.URL)113 HttpURLConnection (java.net.HttpURLConnection)51 IOException (java.io.IOException)50 Test (org.junit.Test)39 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)29 InputStream (java.io.InputStream)27 HostnameVerifier (javax.net.ssl.HostnameVerifier)23 SSLContext (javax.net.ssl.SSLContext)23 OutputStream (java.io.OutputStream)20 MockResponse (com.google.mockwebserver.MockResponse)19 InputStreamReader (java.io.InputStreamReader)19 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)19 URLConnection (java.net.URLConnection)17 BufferedReader (java.io.BufferedReader)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 MalformedURLException (java.net.MalformedURLException)13 Proxy (java.net.Proxy)13 MockResponse (okhttp3.mockwebserver.MockResponse)13