List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory
public void setSSLSocketFactory(SSLSocketFactory sf)
From source file:count.ly.messaging.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { String urlStr = serverURL_ + "/i?"; if (!eventData.contains("&crash=")) urlStr += eventData;//from ww w. ja v a 2 s.c o m final URL url = new URL(urlStr); final HttpURLConnection conn; if (Countly.publicKeyPinCertificates == null) { conn = (HttpURLConnection) url.openConnection(); } else { HttpsURLConnection c = (HttpsURLConnection) url.openConnection(); c.setSSLSocketFactory(sslContext_.getSocketFactory()); conn = c; } conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false); conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else if (eventData.contains("&crash=")) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Using post because of crash"); } conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(eventData); writer.flush(); writer.close(); os.close(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.vmware.photon.controller.deployer.deployengine.HttpFileServiceClient.java
private HttpsURLConnection createHttpConnection(URL destinationURL, String requestMethod) throws Exception { final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override/*from ww w . ja va 2 s .c om*/ 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; } } }; final HostnameVerifier trustAllHostnames = (String hostname, SSLSession sslSession) -> true; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); String authType = "Basic " + new String(Base64.encodeBase64((this.userName + ":" + this.password).getBytes())); HttpsURLConnection httpConnection = (HttpsURLConnection) destinationURL.openConnection(); httpConnection.setSSLSocketFactory(sslContext.getSocketFactory()); httpConnection.setHostnameVerifier(trustAllHostnames); httpConnection.setRequestMethod(requestMethod); httpConnection.setRequestProperty("Authorization", authType); return httpConnection; }
From source file:org.apache.hadoop.security.ssl.SSLFactory.java
/** * If the given {@link HttpURLConnection} is an {@link HttpsURLConnection} * configures the connection with the {@link SSLSocketFactory} and * {@link HostnameVerifier} of this SSLFactory, otherwise does nothing. * * @param conn the {@link HttpURLConnection} instance to configure. * @return the configured {@link HttpURLConnection} instance. * * @throws IOException if an IO error occurred. *///from w ww . java2 s.c om @Override public HttpURLConnection configure(HttpURLConnection conn) throws IOException { if (conn instanceof HttpsURLConnection) { HttpsURLConnection sslConn = (HttpsURLConnection) conn; try { sslConn.setSSLSocketFactory(createSSLSocketFactory()); } catch (GeneralSecurityException ex) { throw new IOException(ex); } sslConn.setHostnameVerifier(getHostnameVerifier()); conn = sslConn; } return conn; }
From source file:it.serverSystem.HttpsTest.java
private void connectUntrusted() throws Exception { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; }// w w w . j a v a 2s . c om public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager // SSLv3 is disabled since SQ 4.5.2 : https://jira.codehaus.org/browse/SONAR-5860 SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory untrustedSocketFactory = sc.getSocketFactory(); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; URL url = new URL("https://localhost:" + httpsPort + "/sessions/login"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(true); connection.setSSLSocketFactory(untrustedSocketFactory); connection.setHostnameVerifier(allHostsValid); InputStream input = connection.getInputStream(); checkCookieFlags(connection); try { String html = IOUtils.toString(input); assertThat(html).contains("<body"); } finally { IOUtils.closeQuietly(input); } }
From source file:de.escidoc.core.test.sb.HttpRequester.java
/** * Sends request with given method and given body to given URI and returns result as String. * * @param resource String resource// www . ja v a 2 s . co m * @param method String method * @param body String body * @return String response * @throws Exception e */ private String requestSsl(final String resource, final String method, final String body) throws Exception { URL url; InputStream is = null; StringBuffer response = new StringBuffer(); // Open Connection to given resource url = new URL(domain + resource); TrustManager[] tm = { new RelaxedX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory sslSF = sslContext.getSocketFactory(); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(sslSF); // Set Basic-Authentication Header if (securityHandle != null && !securityHandle.equals("")) { String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET))); con.setRequestProperty("Authorization", "Basic " + encoding); } // Set request-method and timeout con.setRequestMethod(method.toUpperCase(Locale.ENGLISH)); con.setReadTimeout(TIMEOUT); // If PUT or POST, write given body in Output-Stream if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) { con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write(body.getBytes(ClientBase.DEFAULT_CHARSET)); out.flush(); out.close(); } // Request is = con.getInputStream(); // Read response String currentLine = null; BufferedReader br = new BufferedReader(new InputStreamReader(is)); while ((currentLine = br.readLine()) != null) { response.append(currentLine + "\n"); } is.close(); return response.toString(); }
From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java
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; }
From source file:org.kontalk.upload.HTPPFileUploadConnection.java
private void setupClient(HttpsURLConnection conn, long length, String mime, boolean acceptAnyCertificate) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, NoSuchProviderException, IOException { conn.setSSLSocketFactory( ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate)); if (acceptAnyCertificate) conn.setHostnameVerifier(new AllowAllHostnameVerifier()); conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream"); // bug caused by Lighttpd //conn.setRequestProperty("Expect", "100-continue"); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setDoOutput(true);// w ww. j a v a 2 s . c om conn.setDoInput(true); conn.setRequestProperty("Content-Length", String.valueOf(length)); conn.setRequestMethod("PUT"); }
From source file:io.github.retz.web.Client.java
public int getBinaryFile(int id, String file, OutputStream out) throws IOException { String date = TimestampHelper.now(); String resource = "/job/" + id + "/download?path=" + file; AuthHeader header = authenticator.header("GET", "", date, resource); URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode! LOG.info("Fetching {}", url); HttpURLConnection conn;/*w w w .j a va2s . c o m*/ conn = (HttpURLConnection) url.openConnection(); //LOG.info("classname> {}", conn.getClass().getName()); if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) { if (verboseLog) { LOG.warn( "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); } HttpsURLConnection sslCon = (HttpsURLConnection) conn; if (socketFactory != null) { sslCon.setSSLSocketFactory(socketFactory); } if (hostnameVerifier != null) { sslCon.setHostnameVerifier(hostnameVerifier); } } conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("Authorization", header.buildHeader()); conn.setRequestProperty("Date", date); conn.setRequestProperty("Content-md5", ""); conn.setDoInput(true); String s2s = authenticator.string2sign("GET", "", date, resource); LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s); if (conn.getResponseCode() != 200) { if (verboseLog) { LOG.warn("HTTP Response:", conn.getResponseMessage()); } if (conn.getResponseCode() < 200) { throw new AssertionError(conn.getResponseMessage()); } else if (conn.getResponseCode() == 404) { throw new FileNotFoundException(url.toString()); } else { String message; try { Response response = MAPPER.readValue(conn.getErrorStream(), Response.class); message = response.status(); LOG.error(message, response); } catch (JsonProcessingException e) { message = e.toString(); LOG.error(message, e); } throw new UnknownError(message); } } int size = conn.getContentLength(); if (size < 0) { throw new IOException("Illegal content length:" + size); } else if (size == 0) { // not bytes to save; return 0; } try { return IOUtils.copy(conn.getInputStream(), out); } finally { conn.disconnect(); } }
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;/*ww w . j a v a 2s . com*/ 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()); } } }
From source file:com.apteligent.ApteligentJavaClient.java
private HttpsURLConnection sendGetRequest(String endpoint, String urlParameters) throws IOException { // build connection object for GET request URL obj = new URL(endpoint + urlParameters); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(false);/*from www . j a va2s .co m*/ conn.setDoInput(true); conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestMethod("GET"); return conn; }