Java Code Examples for javax.net.ssl.HttpsURLConnection#setSSLSocketFactory()

The following examples show how to use javax.net.ssl.HttpsURLConnection#setSSLSocketFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URLType.java    From webdsl with Apache License 2.0 7 votes vote down vote up
protected static void setAcceptAllVerifier(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {

        // Create the socket factory.
        // Reusing the same socket factory allows sockets to be
        // reused, supporting persistent connections.
        if( null == sslSocketFactory) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, ALL_TRUSTING_TRUST_MANAGER, new java.security.SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        }

        connection.setSSLSocketFactory(sslSocketFactory);

        // Since we may be using a cert with a different name, we need to ignore
        // the hostname as well.
        connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    }
 
Example 2
Source File: NetHttpTransport.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
protected NetHttpRequest buildRequest(String method, String url) throws IOException {
  Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method);
  // connection with proxy settings
  URL connUrl = new URL(url);
  HttpURLConnection connection = connectionFactory.openConnection(connUrl);
  connection.setRequestMethod(method);
  // SSL settings
  if (connection instanceof HttpsURLConnection) {
    HttpsURLConnection secureConnection = (HttpsURLConnection) connection;
    if (hostnameVerifier != null) {
      secureConnection.setHostnameVerifier(hostnameVerifier);
    }
    if (sslSocketFactory != null) {
      secureConnection.setSSLSocketFactory(sslSocketFactory);
    }
  }
  return new NetHttpRequest(connection);
}
 
Example 3
Source File: InsecureStreamProvider.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream openStream(String url, Map<String, String> headers, int connectTimeout, int readTimeout) throws IOException {
    URLConnection connection = openConnection(url, headers, connectTimeout, readTimeout);
    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConnection = HttpsURLConnection.class.cast(connection);
        httpsConnection.setHostnameVerifier(INSECURE_HOSTNAME_VERIFIER);
        httpsConnection.setSSLSocketFactory(factory);
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("Using HttpsURLConnection with SSLSocketFactory [%s] for url [%s].", factory, url));
        }
    } else {
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("Using URLConnection for url [%s].", url));
        }
    }
    return connection.getInputStream();
}
 
Example 4
Source File: HttpsSocketFacTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();
    URL url = new URL("https://localhost:" + address.getPort() + "/test6614957/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    SimpleSSLSocketFactory sssf = new SimpleSSLSocketFactory();
    uc.setSSLSocketFactory(sssf);
    uc.setHostnameVerifier(new AllHostnameVerifier());
    InputStream is = uc.getInputStream();

    byte[] ba = new byte[1024];
    int read = 0;
    while ((read = is.read(ba)) != -1) {
        System.out.println(new String(ba, 0, read));
    }

    System.out.println("SimpleSSLSocketFactory.socketCreated = " + sssf.socketCreated);
    System.out.println("SimpleSSLSocketFactory.socketWrapped = " + sssf.socketWrapped);

    if (!sssf.socketCreated)
        throw new RuntimeException("Failed: Socket Factory not being called to create Socket");
}
 
Example 5
Source File: TestPhases.java    From testgrid with Apache License 2.0 6 votes vote down vote up
private void validateLog(String testPlan) throws Exception {
    String webPage = TestProperties.tgDashboardApiUrl + "/test-plans/log/" + testPlan;

    URL url = new URL(webPage);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setRequestProperty("Authorization", TestProperties.tgApiToken);
    SSLSocketFactory sslSocketFactory = createSslSocketFactory();
    connection.setSSLSocketFactory(sslSocketFactory);

    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        if (response.toString().contains(testPlan)) {
            logger.info("Correct log is found");
        } else {
            Assert.fail("Correct log is not found");
        }
    }
}
 
Example 6
Source File: UnsafeConnectionBuilder.java    From react-native-app-auth with MIT License 6 votes vote down vote up
@NonNull
@Override
public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException {
    Preconditions.checkNotNull(uri, "url must not be null");
    Preconditions.checkArgument(HTTP.equals(uri.getScheme()) || HTTPS.equals(uri.getScheme()),
            "scheme or uri must be http or https");
    HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
    conn.setConnectTimeout(CONNECTION_TIMEOUT_MS);
    conn.setReadTimeout(READ_TIMEOUT_MS);
    conn.setInstanceFollowRedirects(false);

    if (conn instanceof HttpsURLConnection && TRUSTING_CONTEXT != null) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        httpsConn.setSSLSocketFactory(TRUSTING_CONTEXT.getSocketFactory());
        httpsConn.setHostnameVerifier(ANY_HOSTNAME_VERIFIER);
    }

    return conn;
}
 
Example 7
Source File: FileTransfer.java    From reader with MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 8
Source File: AbstractTestSecure.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
protected HttpsURLConnection openUrlConnection(String url, SSLContext sslContext) throws IOException {
    DockerPort dockerPort = docker.containers().container("squid").port(3128);
    HttpsURLConnection httpURLConnection = (HttpsURLConnection) new URL(url).openConnection(
            new Proxy(Proxy.Type.HTTP, new InetSocketAddress(dockerPort.getIp(), dockerPort.getExternalPort())));
    httpURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    return httpURLConnection;
}
 
Example 9
Source File: TestSSLHttpServer.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 *  Test that verifies headers can be up to 64K long.
 *  The test adds a 63K header leaving 1K for other headers.
 *  This is because the header buffer setting is for ALL headers,
 *  names and values included. */
@Test
public void testLongHeader() throws Exception {
  URL url = new URL(baseUrl, "/longheader");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
  testLongHeader(conn);
}
 
Example 10
Source File: FileTransfer.java    From reacteu-app with MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 11
Source File: FileTransfer.java    From jpHolo with MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 12
Source File: KMSClientProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
private HttpURLConnection configureConnection(HttpURLConnection conn)
    throws IOException {
  if (sslFactory != null) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  return conn;
}
 
Example 13
Source File: UntrustedSSLHelper.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
static void trustAllCerts(HttpsURLConnection urlConnection) {
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        urlConnection.setSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        System.err.println("Cannot instantiate trust-all ssl context: " + e);
    }
}
 
Example 14
Source File: FileTransfer.java    From reader with MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 15
Source File: HttpsUtils.java    From af-pay with Apache License 2.0 5 votes vote down vote up
public static void initHttps(HttpsURLConnection connection, String protocol) {
    try {
        SSLContext context = SSLContext.getInstance(TextUtils.isEmpty(protocol) ? "TLS" : protocol);
        context.init(null, new TrustManager[]{new EmptyTrustManager()}, null);
        connection.setSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: HttpsRequestFactory.java    From yue-library with Apache License 2.0 5 votes vote down vote up
private void prepareHttpsConnection(HttpsURLConnection connection) {
	connection.setHostnameVerifier(new SkipHostnameVerifier());
	try {
		connection.setSSLSocketFactory(createSslSocketFactory());
	} catch (Exception ex) {
		// Ignore
	}
}
 
Example 17
Source File: StatisticManager.java    From Rumble with GNU General Public License v3.0 4 votes vote down vote up
public void onEventAsync(LinkLayerStarted event) {
    if(!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;

    if(RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if(!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(RumbleApplication.getContext()
                    .getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex)
        {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}
 
Example 18
Source File: WxstoreUtils.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
public static JSONObject httpRequest2(String requestUrl,
		String requestMethod, byte[] outputStr) {
	JSONObject jsonObject = null;
	StringBuffer buffer = new StringBuffer();
	try {
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new SecureRandom());

		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL url = new URL(requestUrl);
		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
				.openConnection();
		httpUrlConn.setSSLSocketFactory(ssf);

		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);

		httpUrlConn.setRequestMethod(requestMethod);

		if ("GET".equalsIgnoreCase(requestMethod)) {
			httpUrlConn.connect();
		}

		if (null != outputStr) {
			OutputStream outputStream = httpUrlConn.getOutputStream();

			outputStream.write(outputStr);
			outputStream.close();
		}

		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(
				inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(
				inputStreamReader);

		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();

		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		jsonObject = JSONObject.fromObject(buffer.toString());
	} catch (ConnectException ce) {
		System.out.print("Weixin server connection timed out.");
	} catch (Exception e) {
		System.out.print("https request error:{}" + e.getMessage());
	}
	return jsonObject;
}
 
Example 19
Source File: TenpayHttpClient.java    From jframe with Apache License 2.0 3 votes vote down vote up
protected void httpsPostMethod(String url, byte[] postData, SSLContext sslContext) throws IOException {

        SSLSocketFactory sf = sslContext.getSocketFactory();

        HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);

        conn.setSSLSocketFactory(sf);

        this.doPost(conn, postData);

    }
 
Example 20
Source File: AbstractTimelineMetricsSink.java    From ambari-metrics with Apache License 2.0 3 votes vote down vote up
protected HttpsURLConnection getSSLConnection(String spec)
  throws IOException, IllegalStateException {

  HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection());

  connection.setSSLSocketFactory(sslSocketFactory);

  return connection;
}