List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:client.lib.Client.java
public Client() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { X509Certificate[] myTrustedAnchors = new X509Certificate[0]; return myTrustedAnchors; }/* w w w . j a va2 s. co m*/ @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); http2Client = new OkHttpClient(); http2Client.setSslSocketFactory(sslSocketFactory); http2Client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); httpClient = http2Client.clone(); httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2)); }
From source file:ru.elifantiev.yandex.YandexSSLSocketFactory.java
YandexSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { }// w w w . j av a2s. co m public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { for (X509Certificate cert : certificates) cert.checkValidity(); } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); }
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 ww . j a 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.cellobject.oikos.util.IISSLSocketFactory.java
public IISSLSocketFactory(final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); final TrustManager tm = new X509TrustManager() { @Override/*from ww w . j a v a2s.c o m*/ public void checkClientTrusted(final X509Certificate[] certificate, final String authType) throws CertificateException { } @Override public void checkServerTrusted(final X509Certificate[] certificate, final String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); }
From source file:com.bright.json.MySSLSocketFactory.java
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }//from w w w. java2 s.co m public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); }
From source file:fi.iki.dezgeg.matkakorttiwidget.matkakortti.NonverifyingSSLSocketFactory.java
public NonverifyingSSLSocketFactory(KeyStore truststore) throws Exception { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }//w w w . ja v a 2s. c o m public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); }
From source file:com.linkedin.pinot.monitor.util.HttpUtils.java
/** * {/*from w w w . j a va2s.co m*/ text: "", attachments: [{ title: "", description: "??", url: "", color: "warning|info|primary|error|muted|success" }] displayUser: { name: "??", avatarUrl: "??" } } * @param text * @return */ public static void postMonitorData(String text) { SSLContext sslContext = null; HttpClient client = new DefaultHttpClient(); try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }, new SecureRandom()); } catch (Exception e) { e.printStackTrace(); } SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); HttpPost httpPost = new HttpPost("https://hooks.pubu.im/services/1d2d2rwn8wb6sx"); Map<String, Object> map = new HashMap<String, Object>(); Map<String, String> sender = new HashMap<String, String>(); sender.put("name", "Monitor"); map.put("displayUser", sender); List<String> list = new ArrayList<String>(); map.put("attachments", list); try { map.put("text", text); InputStreamEntity httpentity = new InputStreamEntity( new ByteArrayInputStream(mapper.writeValueAsBytes(map)), mapper.writeValueAsBytes(map).length); httpPost.setEntity(httpentity); httpPost.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } finally { // } }
From source file:com.payu.sdk.helper.WebClientDevWrapper.java
/** * Wraps a default and secure httpClient * * @param base the original httpClient//from ww w . j a va 2s . co m * @return the hhtpClient wrapped * @throws ConnectionException */ public static HttpClient wrapClient(HttpClient base) throws ConnectionException { try { SSLContext ctx = SSLContext.getInstance(Constants.SSL_PROVIDER); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", Constants.HTTPS_PORT, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { throw new ConnectionException("Invalid SSL connection", ex); } }
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; }//from ww w. j av a2 s . co m 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:org.fineract.module.stellar.fineractadapter.RestAdapterProvider.java
OkHttpClient createClient() { final OkHttpClient client = new OkHttpClient(); final TrustManager[] certs = new TrustManager[] { new X509TrustManager() { @Override/*from w w w .j a v a 2 s. co m*/ public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } } }; SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); ctx.init(null, certs, new SecureRandom()); } catch (final java.security.GeneralSecurityException ignored) { } try { client.setHostnameVerifier((hostname, session) -> true); if (ctx != null) { client.setSslSocketFactory(ctx.getSocketFactory()); } } catch (final Exception ignored) { } return client; }