List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory
public void setSSLSocketFactory(SSLSocketFactory sf)
From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java
private boolean ping() { log.debug("Attempting to ping {}", url); try {/*from w w w. ja v a 2 s . c o m*/ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(connectionTimeoutSeconds * 1000); connection.setReadTimeout(connectionTimeoutSeconds * 1000); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); if (sslService != null && connection instanceof HttpsURLConnection) { SSLService service = sslService.service(); if (service != null) { SSLSocketFactory factory = service.getSolarInSocketFactory(); if (factory != null) { HttpsURLConnection sslConnection = (HttpsURLConnection) connection; sslConnection.setSSLSocketFactory(factory); } } } int responseCode = connection.getResponseCode(); return (responseCode >= 200 && responseCode < 400); } catch (IOException e) { log.info("Error pinging {}: {}", url, e.getMessage()); return false; } }
From source file:com.apteligent.ApteligentJavaClient.java
private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException { // build conn object for POST request URL obj = new URL(endpoint); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(true);/*from w ww. j av a2 s .co m*/ conn.setDoInput(true); conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken()); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length)); conn.setRequestMethod("POST"); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); return conn; }
From source file:com.apteligent.ApteligentJavaClient.java
/*********************************************************************************************************************/ private Token auth(String email, String password) throws IOException { String urlParameters = "grant_type=password&username=" + email + "&password=" + password; URL obj = new URL(API_TOKEN); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(true);/*from ww w. j ava2 s .c o m*/ conn.setDoInput(true); //add request header String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes())); conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth)); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); conn.setRequestMethod("POST"); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // read token JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createParser(conn.getInputStream()); ObjectMapper mapper = getObjectMapper(); Token token = mapper.readValue(jp, Token.class); return token; }
From source file:org.openhab.action.openwebif.internal.impl.OpenWebIfCommunicator.java
/** * Executes the http request and parses the returned stream. *///from w w w.j a v a 2 s. c o m @SuppressWarnings("unchecked") private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException { HttpURLConnection con = null; try { logger.trace("Request [{}]: {}", config.getName(), url); con = (HttpURLConnection) new URL(url).openConnection(); con.setConnectTimeout(CONNECTION_TIMEOUT); con.setReadTimeout(10000); if (config.hasLogin()) { String userpass = config.getUser() + ":" + config.getPassword(); String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes()); con.setRequestProperty("Authorization", basicAuth); } if (con instanceof HttpsURLConnection) { HttpsURLConnection sCon = (HttpsURLConnection) con; TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() }; SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[0], trustManager, new SecureRandom()); sCon.setSSLSocketFactory(context.getSocketFactory()); sCon.setHostnameVerifier(new AllowAllHostnameVerifier()); } StringWriter sw = new StringWriter(); IOUtils.copy(con.getInputStream(), sw); con.disconnect(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { String response = sw.toString(); logger.trace("Response: [{}]: {}", config.getName(), response); Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller(); return (T) um.unmarshal(new StringReader(response)); } else { throw new IOException(con.getResponseMessage()); } } catch (JAXBException ex) { throw new IOException(ex.getMessage(), ex); } catch (GeneralSecurityException ex) { throw new IOException(ex.getMessage(), ex); } finally { if (con != null) { con.disconnect(); } } }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) { HttpsURLConnection urlConnection = conn; try {//from w w w . j a v a2 s .co m KeyStore localTrustStore; localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.emm_truststore); localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray()); TrustManagerFactory tmf; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(localTrustStore); SSLContext sslCtx; sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, tmf.getTrustManagers(), null); urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory()); return urlConnection; } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); return null; } }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
private HttpsURLConnection openSecureConnection(URL url) throws Exception { InputStream keyStream = new FileInputStream(truststorePath); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory.getInstance( Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm)); trustFactory.init(keystore);//from w w w .j av a2 s. c om SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustFactory.getTrustManagers(), null); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setSSLSocketFactory(context.getSocketFactory()); httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return httpsURLConnection; }
From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java
private String processGetRequest(URL url, String keyStore, String keyStorePassword) throws GeneralSecurityException, IOException { SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(sslFactory); con.setRequestMethod("GET"); con.addRequestProperty("x-ms-version", "2014-04-01"); InputStream responseStream = (InputStream) con.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStreamSafely(responseStream, os); return os.toString("UTF-8"); }
From source file:fi.hip.sicx.store.HIPStoreClient.java
private HttpURLConnection getConnection(String path) throws Exception { LocalProperties props = LocalProperties.getInstance(); URL url = new URL(props.getProperty("hipstore.url", "https://localhost:7443/remotestore") + path); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); if (uc instanceof HttpsURLConnection) { HttpsURLConnection conn = (HttpsURLConnection) uc; conn.setSSLSocketFactory(wrapper.getSocketFactory()); }//from w ww . java 2 s .com //conn.setRequestProperty("Connection","Keep-Alive"); return uc; }
From source file:org.jasig.cas.util.SimpleHttpClient.java
@Override public boolean isValidEndPoint(final URL url) { HttpURLConnection connection = null; InputStream is = null;//from www . j ava 2 s.com try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(this.connectionTimeout); connection.setReadTimeout(this.readTimeout); connection.setInstanceFollowRedirects(this.followRedirects); if (connection instanceof HttpsURLConnection) { final HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; if (this.sslSocketFactory != null) { httpsConnection.setSSLSocketFactory(this.sslSocketFactory); } if (this.hostnameVerifier != null) { httpsConnection.setHostnameVerifier(this.hostnameVerifier); } } connection.connect(); final int responseCode = connection.getResponseCode(); for (final int acceptableCode : this.acceptableCodes) { if (responseCode == acceptableCode) { LOGGER.debug("Response code from server matched {}.", responseCode); return true; } } LOGGER.debug("Response Code did not match any of the acceptable response codes. Code returned was {}", responseCode); // if the response code is an error and we don't find that error acceptable above: if (responseCode == 500) { is = connection.getInputStream(); final String value = IOUtils.toString(is); LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(), value); } } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); if (connection != null) { connection.disconnect(); } } return false; }
From source file:com.adobe.phonegap.contentsync.Sync.java
/** * 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. *///from ww w. j a va 2 s .c om 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; }