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:gov.nih.nci.nbia.StandaloneDMDispatcher.java
private void downloadInstaller(String downloadUrl) { String fileName = getInstallerName(downloadUrl); InputStream in;/* w w w . j a v a2 s.c o m*/ // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { // here is the place to check client certs and throw an // exception if certs are wrong. When there is nothing all certs // accepted. } public void checkServerTrusted(X509Certificate[] certs, String authType) { // here is the place to check server certs and throw an // exception if certs are wrong. When there is nothing all certs // accepted. } } }; // Install the all-trusting trust manager try { 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) { // Here is the palce to check host name against to // certificate owner return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (KeyManagementException | NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { } try { URL url = new URL(downloadUrl); in = url.openStream(); FileOutputStream fos = new FileOutputStream(new File(fileName)); int length = -1; ProgressMonitorInputStream pmis; pmis = new ProgressMonitorInputStream(null, "Downloading new version of installer for NBIA Data Retriever...", in); ProgressMonitor monitor = pmis.getProgressMonitor(); monitor.setMillisToPopup(0); monitor.setMinimum(0); monitor.setMaximum((int) 200000000); // The actual size is much // smaller, // but we have no way to // know // the actual size so picked // this big number byte[] buffer = new byte[1024];// buffer for portion of data from // connection while ((length = pmis.read(buffer)) > 0) { fos.write(buffer, 0, length); } pmis.close(); fos.flush(); fos.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:TestHTTPSource.java
public void doTestHttps(String protocol) throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();//w w w .j a v a2 s . co m List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < 10; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } input.put("MsgNum", String.valueOf(i)); JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8")); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); HttpsURLConnection httpsURLConnection = null; try { TrustManager[] trustAllCerts = { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sc = null; javax.net.ssl.SSLSocketFactory factory = null; if (System.getProperty("java.vendor").contains("IBM")) { sc = SSLContext.getInstance("SSL_TLS"); } else { sc = SSLContext.getInstance("SSL"); } HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; sc.init(null, trustAllCerts, new SecureRandom()); if (protocol != null) { factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol); } else { factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(factory); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); URL sslUrl = new URL("https://0.0.0.0:" + sslPort); httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection(); httpsURLConnection.setDoInput(true); httpsURLConnection.setDoOutput(true); httpsURLConnection.setRequestMethod("POST"); httpsURLConnection.getOutputStream().write(json.getBytes()); int statusCode = httpsURLConnection.getResponseCode(); Assert.assertEquals(200, statusCode); Transaction transaction = channel.getTransaction(); transaction.begin(); for (int i = 0; i < 10; i++) { Event e = channel.take(); Assert.assertNotNull(e); Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum")); } transaction.commit(); transaction.close(); } finally { httpsURLConnection.disconnect(); } }
From source file:org.codice.ddf.itests.common.cometd.CometDClient.java
private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override//from w w w . j a v a 2 s . com public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost()); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); }
From source file:itdelatrisu.opsu.Utils.java
/** * Switches validation of SSL certificates on or off by installing a default * all-trusting {@link TrustManager}.//from w ww . j a va 2s .com * @param enabled whether to validate SSL certificates * @author neu242 (http://stackoverflow.com/a/876785) */ public static void setSSLCertValidation(boolean enabled) { // create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, enabled ? null : trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } }
From source file:org.jenkinsci.plugins.codefresh.CFApi.java
private void secureContext(boolean selfSignedCert) { this.https = true; trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; }/* ww w.jav a 2s . co m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); this.sf = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(this.sf); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (selfSignedCert) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession sslSession) { return true; } }); } }
From source file:com.arm.connector.bridge.transport.HttpTransport.java
@SuppressWarnings("empty-statement") private String doHTTP(String verb, String url_str, String username, String password, String data, String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL, boolean use_api_token, String api_token) { String result = ""; String line = ""; URLConnection connection = null; SSLContext sc = null;/*from ww w . jav a 2s.c o m*/ try { URL url = new URL(url_str); // Http Connection and verb if (doSSL) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (NoSuchAlgorithmException | KeyManagementException e) { // do nothing ; } // open the SSL connction connection = (HttpsURLConnection) (url.openConnection()); ((HttpsURLConnection) connection).setRequestMethod(verb); ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } else { connection = (HttpURLConnection) (url.openConnection()); ((HttpURLConnection) connection).setRequestMethod(verb); } connection.setDoInput(doInput); if (doOutput && data != null && data.length() > 0) { connection.setDoOutput(doOutput); } else { connection.setDoOutput(false); } // enable basic auth if requested if (use_api_token == false && username != null && username.length() > 0 && password != null && password.length() > 0) { String encoding = Base64.encodeBase64String((username + ":" + password).getBytes()); connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding); //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding); } // enable ApiTokenAuth auth if requested if (use_api_token == true && api_token != null && api_token.length() > 0) { // use qualification for the authorization header... connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token); //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token); // Always reset to the established default this.resetAuthorizationQualifier(); } // ETag support if requested if (this.m_etag_value != null && this.m_etag_value.length() > 0) { // set the ETag header value connection.setRequestProperty("ETag", this.m_etag_value); //this.errorLogger().info("ETag Value: " + this.m_etag_value); // Always reset to the established default this.resetETagValue(); } // If-Match support if requested if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) { // set the If-Match header value connection.setRequestProperty("If-Match", this.m_if_match_header_value); //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value); // Always reset to the established default this.resetIfMatchValue(); } // specify content type if requested if (content_type != null && content_type.length() > 0) { connection.setRequestProperty("Content-Type", content_type); connection.setRequestProperty("Accept", "*/*"); } // add Connection: keep-alive (does not work...) //connection.setRequestProperty("Connection", "keep-alive"); // special gorp for HTTP DELETE if (verb != null && verb.equalsIgnoreCase("delete")) { connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE"); } // specify domain if requested if (auth_domain != null && auth_domain.length() > 0) { connection.setRequestProperty("Domain", auth_domain); } // DEBUG dump the headers //if (doSSL) // this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); //else // this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); // specify data if requested - assumes it properly escaped if necessary if (doOutput && data != null && data.length() > 0) { try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) { out.write(data); } } // setup the output if requested if (doInput) { try { try (InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content))) { while ((line = in.readLine()) != null) { result += line; } } } catch (java.io.FileNotFoundException ex) { this.errorLogger().info("HTTP(" + verb + ") empty response (OK)."); result = ""; } } else { // no result expected result = ""; } // save off the HTTP response code... if (doSSL) this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode()); else this.saveResponseCode(((HttpURLConnection) connection).getResponseCode()); // DEBUG //if (doSSL) // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode()); //else // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode()); } catch (IOException ex) { this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage()); result = null; } // return the result return result; }
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void trustSSL() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }/*from w w w . j a v a2s . c om*/ public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // c'est un pb de scurit, il faudrait mettre jour les certifs racine et supprimer le all-trusting trust manager // 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) { System.out.println("Can not install the all-trusting trust manager"); } }
From source file:com.inovex.zabbixmobile.activities.BaseActivity.java
/** * Binds the data service and sets up the action bar. *///from w ww .j ava2 s.com @Override protected void onCreate(Bundle savedInstanceState) { ZaxPreferences prefs = ZaxPreferences.getInstance(getApplicationContext()); if (prefs.isDarkTheme()) setTheme(R.style.AppThemeDark); else setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); finishReceiver = new FinishReceiver(); registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH)); bindService(); // (re-) instantiate progress dialog mLoginProgress = (LoginProgressDialogFragment) getSupportFragmentManager() .findFragmentByTag(LoginProgressDialogFragment.TAG); if (mLoginProgress == null) { mLoginProgress = LoginProgressDialogFragment.getInstance(); } try { SSLContext sc = SSLContext.getInstance("TLS"); MemorizingTrustManager mtm = new MemorizingTrustManager(this); sc.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier( mtm.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * ?// w ww. jav a2s . co m * @param appWorkspace ? * @param source ? * @param target ?? * @param args JSONArray * @param callbackCtx nativejs * * args[2] fileKey ?name file? * args[3] fileName ??? image.jpg? * args[4] mimeType ?mimeimage/jpeg? * args[5] params HTTP????/ * args[6] trustEveryone * args[7] chunkedMode ??????true * @return FileUploadResult */ private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args, XCallbackContext callbackCtx) { XLog.d(CLASS_NAME, "upload " + source + " to " + target); HttpURLConnection conn = null; try { String fileKey = getArgument(args, 2, "file"); String fileName = getArgument(args, 3, "image.jpg"); String mimeType = getArgument(args, 4, "image/jpeg"); JSONObject params = args.optJSONObject(5); if (params == null) { params = new JSONObject(); } boolean trustEveryone = args.optBoolean(6); boolean chunkedMode = args.optBoolean(7) || args.isNull(7); JSONObject headers = args.optJSONObject(8); if (headers == null && params != null) { headers = params.optJSONObject("headers"); } String objectId = args.getString(9); //------------------ URL url = new URL(target); conn = getURLConnection(url, trustEveryone); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); setCookieProperty(conn, target); // ?? handleRequestHeader(headers, conn); byte[] extraBytes = extraBytesFromParams(params, fileKey); String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END; String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE); FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source); int maxBufferSize = XConstant.BUFFER_LEN; if (chunkedMode) { conn.setChunkedStreamingMode(maxBufferSize); } else { int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length; XLog.d(CLASS_NAME, "String Length: " + stringLength); int fixedLength = (int) fileInputStream.getChannel().size() + stringLength; XLog.d(CLASS_NAME, "Content Length: " + fixedLength); conn.setFixedLengthStreamingMode(fixedLength); } // ??? OutputStream ouputStream = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(ouputStream); dos.write(extraBytes); dos.write(fileNameBytes); dos.writeBytes(midParams); XFileUploadResult result = new XFileUploadResult(); FileTransferProgress progress = new FileTransferProgress(); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); long totalBytes = 0; while (bytesRead > 0) { totalBytes += bytesRead; result.setBytesSent(totalBytes); dos.write(buffer, 0, bytesRead); bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (objectId != null) { //?js??object ID? progress.setTotal(bytesAvailable); XLog.d(CLASS_NAME, "total=" + bytesAvailable); progress.setLoaded(totalBytes); progress.setLengthComputable(true); XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); callbackCtx.sendExtensionResult(progressResult); } synchronized (abortTriggered) { if (objectId != null && abortTriggered.contains(objectId)) { abortTriggered.remove(objectId); throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED); } } } dos.writeBytes(tailParams); fileInputStream.close(); dos.flush(); dos.close(); checkConnection(conn); setUploadResult(result, conn); // if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory); } XLog.d(CLASS_NAME, "****** About to return a result from upload"); return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject()); } catch (AbortException e) { JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { XLog.e(CLASS_NAME, e.getMessage()); return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION); } catch (Throwable t) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } finally { if (conn != null) { conn.disconnect(); } } }