List of usage examples for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory
public static void setDefaultSSLSocketFactory(SSLSocketFactory sf)
SSLSocketFactory
inherited by new instances of this class. From source file:sit.web.client.HTTPTrustHelper.java
public static void init(String securityAlgorithm, KeyManager[] kms, TrustManager[] tms) { // Install the all-trusting trust manager try {//from ww w . j a v a 2 s.c o m SSLContext sc = SSLContext.getInstance(securityAlgorithm); sc.init(kms, tms, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception ex) { Logger.getLogger(HttpHelper.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String string, SSLSession ssls) { return true; } }); HttpsURLConnection.setFollowRedirects(true); }
From source file:org.gluu.oxtrust.ldap.service.LinktrackService.java
public String newLink(@NotEmpty String login, @NotEmpty String password, @NotEmpty String link) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }// w ww .jav a 2s .com public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(String.format(CREATE_LINK_URL_PATTERN, login, password, link)); HttpResponse response; try { response = httpclient.execute(httpget); } catch (Exception e) { log.error(String.format("Exception happened during linktrack link " + "creation with username: %s, password: %s," + " link: %s.", login, password, link), e); return null; } String trackedLink = null; if (response.getStatusLine().getStatusCode() == 201) { try { trackedLink = IOUtils.toString(response.getEntity().getContent()); } catch (Exception e) { e.printStackTrace(); } } return trackedLink; }
From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java
public Socket createSocket(String host, int port) throws IOException, UnknownHostException { TrustManager[] trustAllCerts = getTrustManager(); try {// ww w. j ava 2 s . c o m SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); return socketFactory.createSocket(host, port); } catch (Exception ex) { throw new UnknownHostException("Problems to connect " + host + ex.toString()); } }
From source file:com.ethercamp.harmony.util.TrustSSL.java
public static void applyAnother() { try {/*from w w w . ja va 2 s . co m*/ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String authType) throws CertificateException { System.out.println( "x509Certificates = [" + x509Certificates + "], authType = [" + authType + "]"); } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String authType) throws CertificateException { System.out.println( "x509Certificates = [" + x509Certificates + "], authType = [" + authType + "]"); } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager 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) { System.out.println("hostname = [" + hostname + "], session = [" + session + "]"); return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.jevis.commons.driver.DataSourceHelper.java
static public void doTrustToCertificates() throws Exception { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; }// www . ja v a2s. c o m public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) { System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'."); } return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); }
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;/*from w w w .ja v a 2 s .c om*/ URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; 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() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; }// w w w . j ava2s . c o m public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { LoggingUtils.e(LOG_TAG, "Error with SSL connection. " + e.getLocalizedMessage(), null); } }
From source file:com.telefonica.euro_iaas.paasmanager.util.impl.SDCClientConfigImpl.java
public SDCClientConfigImpl(HttpClientConnectionManager httpConnectionManager) { this.httpConnectionManager = httpConnectionManager; clientConfig = new ClientConfig(); clientConfig.register(JacksonFeature.class); clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, httpConnectionManager); ApacheConnectorProvider provider = new ApacheConnectorProvider(); clientConfig.connectorProvider(provider); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 60000); clientConfig.property(ClientProperties.READ_TIMEOUT, 60000); HttpsURLConnection.setDefaultSSLSocketFactory(getStx().getSocketFactory()); }
From source file:com.github.opengarageapp.GarageService.java
/** * Trust every server - dont check for any certificate */// w w w . ja va 2 s .com private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.wso2.carbon.membership.scheme.kubernetes.api.KubernetesHttpsApiEndpoint.java
private static void disableCertificateValidation() { TrustManager[] dummyTrustMgr = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }/*from www . j av a 2 s.c o m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { // do nothing } public void checkServerTrusted(X509Certificate[] certs, String authType) { // do nothing } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier dummyHostVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { // always true return true; } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, dummyTrustMgr, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(dummyHostVerifier); } catch (Exception ignored) { } }