List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier
public void setHostnameVerifier(HostnameVerifier v)
HostnameVerifier
for this instance. From source file:it.jnrpe.plugin.CheckHttp.java
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx);// w ww . j a v a 2 s. co m HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
From source file:org.bremersee.sms.GoyyaSmsService.java
/** * Creates the URL connection.// www. j a v a 2 s . com * * @param url * the URL * @return the URL connection * @throws IOException * if creation of the URL connection fails */ protected HttpURLConnection createHttpURLConnection(final String url) throws IOException { URL sendUrl = new URL(url); HttpURLConnection con = null; if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); con = (HttpURLConnection) sendUrl.openConnection(proxy); if (StringUtils.isNotBlank(proxyUsername)) { String passwd = proxyPassword != null ? proxyPassword : ""; String authValue = proxyUsername + ":" + passwd; String headerValue = Base64.encodeBase64String(authValue.getBytes("utf-8")); con.setRequestProperty("Proxy-Authorization", "Basic " + headerValue); } } else { con = (HttpURLConnection) sendUrl.openConnection(); } try { if (url.toString().toLowerCase().startsWith("https")) { HttpsURLConnection secCon = (HttpsURLConnection) con; secCon.setHostnameVerifier(createAllHostnamesVerifier()); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, createTrustAllManagers(), new SecureRandom()); secCon.setSSLSocketFactory(sc.getSocketFactory()); } } catch (NoSuchAlgorithmException e) { IOException ise = new IOException(e); // log.error("Creating HttpURLConnection failed.", ise); throw ise; } catch (KeyManagementException e) { IOException ise = new IOException(e); // log.error("Creating HttpURLConnection failed.", ise); throw ise; } return con; }
From source file:org.jasig.cas.util.SimpleHttpClient.java
@Override public boolean isValidEndPoint(final URL url) { HttpURLConnection connection = null; InputStream is = null;/*www . ja v a 2 s . co m*/ 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:org.jasig.cas.util.HttpClient.java
public boolean isValidEndPoint(final URL url) { HttpURLConnection connection = null; InputStream is = null;/* w ww . j ava 2 s . c o m*/ 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:io.apiman.gateway.platforms.servlet.connectors.HttpApiConnection.java
/** * Connects to the back end system.// w ww . j a v a 2 s . c o m */ private void connect() throws ConnectorException { try { Set<String> suppressedHeaders = new HashSet<>(SUPPRESSED_REQUEST_HEADERS); String endpoint = api.getEndpoint(); if (endpoint.endsWith("/")) { //$NON-NLS-1$ endpoint = endpoint.substring(0, endpoint.length() - 1); } if (request.getDestination() != null) { endpoint += request.getDestination(); } if (request.getQueryParams() != null && !request.getQueryParams().isEmpty()) { String delim = "?"; //$NON-NLS-1$ for (Entry<String, String> entry : request.getQueryParams()) { endpoint += delim + entry.getKey(); if (entry.getValue() != null) { endpoint += "=" + URLEncoder.encode(entry.getValue(), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ } delim = "&"; //$NON-NLS-1$ } } URL url = new URL(endpoint); OkUrlFactory factory = new OkUrlFactory(client); connection = factory.open(url); boolean isSsl = connection instanceof HttpsURLConnection; if (requiredAuthType == RequiredAuthType.MTLS && !isSsl) { throw new ConnectorException( "Mutually authenticating TLS requested, but insecure endpoint protocol was indicated."); //$NON-NLS-1$ } if (requiredAuthType == RequiredAuthType.BASIC) { BasicAuthOptions options = new BasicAuthOptions(api.getEndpointProperties()); if (options.getUsername() != null && options.getPassword() != null) { if (options.isRequireSSL() && !isSsl) { throw new ConnectorException( "Endpoint security requested (BASIC auth) but endpoint is not secure (SSL)."); //$NON-NLS-1$ } String up = options.getUsername() + ':' + options.getPassword(); StringBuilder builder = new StringBuilder(); builder.append("Basic "); //$NON-NLS-1$ builder.append(Base64.encodeBase64String(up.getBytes())); connection.setRequestProperty("Authorization", builder.toString()); //$NON-NLS-1$ suppressedHeaders.add("Authorization"); //$NON-NLS-1$ } } if (isSsl) { HttpsURLConnection https = (HttpsURLConnection) connection; SSLSocketFactory socketFactory = sslStrategy.getSocketFactory(); https.setSSLSocketFactory(socketFactory); https.setHostnameVerifier(sslStrategy.getHostnameVerifier()); } setConnectTimeout(connection); setReadTimeout(connection); if (request.getType().equalsIgnoreCase("PUT") || request.getType().equalsIgnoreCase("POST")) { //$NON-NLS-1$ //$NON-NLS-2$ connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod(request.getType()); // Set the request headers for (Entry<String, String> entry : request.getHeaders()) { String hname = entry.getKey(); String hval = entry.getValue(); if (!suppressedHeaders.contains(hname)) { connection.setRequestProperty(hname, hval); } } // Set or reset mandatory headers connection.setRequestProperty("Host", url.getHost() + determinePort(url)); //$NON-NLS-1$ connection.connect(); connected = true; } catch (IOException e) { throw new ConnectorException(e); } }
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
private SSLContext setSSLCallback(ISSLCertificateCallback sslAuthorizationCallback, URL url, HttpsURLConnection connection) { X509TrustManager trustManager = null; if (sslAuthorizationCallback != null) { connection.setHostnameVerifier(new CallbackHostnameVerifier()); trustManager = createCallbackTrustManager(sslAuthorizationCallback, connection); }// w w w . ja v a2s . c om try { SSLContext sslContext = SSLUtils.getSSLContext(trustManager); connection.setSSLSocketFactory(sslContext.getSocketFactory()); return sslContext; } catch (GeneralSecurityException e) { LOGGER.warn("Could not install trust manager callback", e); ; return null; } }
From source file:org.kontalk.upload.KontalkBoxUploadConnection.java
private void setupClient(HttpsURLConnection conn, String mime, boolean encrypted, boolean acceptAnyCertificate) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, NoSuchProviderException, IOException { conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));/* www. j a v a2s .com*/ if (acceptAnyCertificate) conn.setHostnameVerifier(new AllowAllHostnameVerifier()); conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream"); if (encrypted) conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted"); // bug caused by Lighttpd conn.setRequestProperty("Expect", "100-continue"); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); }
From source file:android.webkit.cts.TestWebServer.java
private URLConnection openConnection(URL url) throws IOException, NoSuchAlgorithmException, KeyManagementException { if (mSsl) {/* w ww .j a va 2s . co m*/ // Install hostname verifiers and trust managers that don't do // anything in order to get around the client not trusting // the test server due to a lack of certificates. HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new TestHostnameVerifier()); SSLContext context = SSLContext.getInstance("TLS"); TestTrustManager trustManager = new TestTrustManager(); context.init(null, new TestTrustManager[] { trustManager }, null); connection.setSSLSocketFactory(context.getSocketFactory()); return connection; } else { return url.openConnection(); } }
From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java
private void sendHttpMessage() { if (mIsBitmap) { Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url); if (bitmap != null) { events.onHttpComplete(bitmap); return; }//from w ww . ja v a2 s . co m } X509TrustManager trustManager = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } HttpsURLConnection connection = null; try { URL urlObj = new URL(url); connection = (HttpsURLConnection) urlObj.openConnection(); connection.setSSLSocketFactory(noSSLv3Factory); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); byte[] postData = new byte[0]; if (message != null) { postData = message.getBytes("UTF-8"); } if (msCookieManager.getCookieStore().getCookies().size() > 0) { // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';' connection.setRequestProperty("Cookie", TextUtils.join(";", msCookieManager.getCookieStore().getCookies())); } /*if (method.equals("PATCH")) { connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); connection.setRequestMethod("POST"); } else {*/ connection.setRequestMethod(method); //} if (authorization.length() != 0) { connection.setRequestProperty("Authorization", authorization); } connection.setUseCaches(false); connection.setDoInput(true); connection.setConnectTimeout(HTTP_TIMEOUT_MS); connection.setReadTimeout(HTTP_TIMEOUT_MS); // TODO(glaznev) - query request origin from pref_room_server_url_key preferences. //connection.addRequestProperty("origin", HTTP_ORIGIN); boolean doOutput = false; if (method.equals("POST") || method.equals("PATCH")) { doOutput = true; connection.setDoOutput(true); connection.setFixedLengthStreamingMode(postData.length); } if (contentType == null) { connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); } else { connection.setRequestProperty("Content-Type", contentType); } // Send POST request. if (doOutput && postData.length > 0) { OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); } // Get response. int responseCode = 200; try { connection.getResponseCode(); } catch (IOException e) { } getCookies(connection); InputStream responseStream; if (responseCode > 400) { responseStream = connection.getErrorStream(); } else { responseStream = connection.getInputStream(); } String responseType = connection.getContentType(); if (responseType.startsWith("image/")) { Bitmap bitmap = BitmapFactory.decodeStream(responseStream); if (mIsBitmap && bitmap != null) { ThumbnailsCacheManager.addBitmapToCache(url, bitmap); } events.onHttpComplete(bitmap); } else { String response = drainStream(responseStream); events.onHttpComplete(response); } responseStream.close(); connection.disconnect(); } catch (SocketTimeoutException e) { events.onHttpError("HTTP " + method + " to " + url + " timeout"); } catch (IOException e) { if (connection != null) { connection.disconnect(); } events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage()); } catch (ClassCastException e) { e.printStackTrace(); } }