List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory
public void setSSLSocketFactory(SSLSocketFactory sf)
From source file:it.govpay.core.utils.client.BasicClient.java
private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl) throws ClientException { // Creazione Connessione int responseCode; HttpURLConnection connection = null; byte[] msg = null; GpContext ctx = GpThreadLocal.get(); String urlString = url.toExternalForm(); if (isAzioneInUrl) { if (!urlString.endsWith("/")) urlString = urlString.concat("/"); try {//from ww w . ja v a 2 s . co m url = new URL(urlString.concat(azione)); } catch (MalformedURLException e) { throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e); } } try { Message requestMsg = new Message(); requestMsg.setType(MessageType.REQUEST_OUT); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (soap) { connection.setRequestProperty("SOAPAction", "\"" + azione + "\""); requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\"")); } requestMsg.setContentType("text/xml"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestMethod("POST"); // Imposta Contesto SSL se attivo if (sslContext != null) { HttpsURLConnection httpsConn = (HttpsURLConnection) connection; httpsConn.setSSLSocketFactory(sslContext.getSocketFactory()); HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled(); httpsConn.setHostnameVerifier(disabilitato); } // Imposta l'autenticazione HTTP Basic se attiva if (ishttpBasicEnabled) { Base64 base = new Base64(); String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoding); requestMsg.addHeader(new Property("Authorization", "Basic " + encoding)); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (soap) { SOAPUtils.writeMessage(body, header, baos); } else { JaxbUtils.marshal(body, baos); } ctx.getIntegrationCtx().setMsg(baos.toByteArray()); invokeOutHandlers(); if (log.getLevel().isMoreSpecificThan(Level.TRACE)) { StringBuffer sb = new StringBuffer(); for (String key : connection.getRequestProperties().keySet()) { sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key)); } sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg())); log.trace(sb.toString()); } requestMsg.setContent(ctx.getIntegrationCtx().getMsg()); ctx.getContext().getRequest().setOutDate(new Date()); ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length)); ctx.log(requestMsg); connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg()); } catch (Exception e) { throw new ClientException(e); } try { responseCode = connection.getResponseCode(); ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode)); } catch (Exception e) { throw new ClientException(e); } Message responseMsg = new Message(); responseMsg.setType(MessageType.RESPONSE_IN); for (String key : connection.getHeaderFields().keySet()) { if (connection.getHeaderFields().get(key) != null) { if (key == null) responseMsg .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0))); else if (connection.getHeaderFields().get(key).size() == 1) responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0))); else responseMsg.addHeader( new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key)))); } } try { if (responseCode < 300) { try { if (connection.getInputStream() == null) { return null; } msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream()) : new byte[] {}; if (msg.length > 0) responseMsg.setContent(msg); return msg; } catch (Exception e) { throw new ClientException("Messaggio di risposta non valido", e); } } else { try { msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream()) : new byte[] {}; responseMsg.setContent(msg); } catch (IOException e) { msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes(); } finally { log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode + "]\nRisposta: " + new String(msg)); } throw new ClientException("Ricevuto [HTTP " + responseCode + "]"); } } finally { if (responseMsg != null) { ctx.getContext().getResponse().setInDate(new Date()); ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length); ctx.log(responseMsg); } if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null && connection.getHeaderFields() != null) { StringBuffer sb = new StringBuffer(); for (String key : connection.getHeaderFields().keySet()) { sb.append("\n\t" + key + ": " + connection.getHeaderField(key)); } sb.append("\n" + new String(msg)); log.trace(sb.toString()); } } }
From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java
/** * //from w w w . j a v a2 s . c o m * @param url * @return URLConnection * @throws IOException * @throws CertificateException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException */ private URLConnection getUrlConnection(URL url) throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, KeyManagementException { final URLConnection orgcon = url.openConnection(); if (orgcon instanceof HttpsURLConnection) { HttpsURLConnection con = (HttpsURLConnection) orgcon; con.setHostnameVerifier(new SimpleVerifier()); con.setSSLSocketFactory(getSSLFactory()); } return orgcon; }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Prepares a connection to the server.// ww w . j a va 2s .com * @param extraHeaders extra headers to add to the request * @return the unopened connection * @throws IOException */ protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException { // create URLConnection HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy); con.setConnectTimeout(connectionTimeoutMillis); con.setReadTimeout(readTimeoutMillis); con.setAllowUserInteraction(false); con.setDefaultUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setInstanceFollowRedirects(true); con.setRequestMethod("POST"); // do stuff for ssl if (HttpsURLConnection.class.isInstance(con)) { HttpsURLConnection https = HttpsURLConnection.class.cast(con); if (hostNameVerifier != null) { https.setHostnameVerifier(hostNameVerifier); } if (sslContext != null) { https.setSSLSocketFactory(sslContext.getSocketFactory()); } } // add headers con.setRequestProperty("Content-Type", "application/json-rpc"); for (Entry<String, String> entry : headers.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } for (Entry<String, String> entry : extraHeaders.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } // return it return con; }
From source file:org.apache.hadoop.http.TestSSLHttpServer.java
/** * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA, * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA, * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not * available for negotiation during SSL connection. *//*from w w w . j ava2 s . c om*/ @Test public void testExcludedCiphers() throws Exception { URL url = new URL(baseUrl, "/echo?a=b&c=d"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory(); PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory( sslSocketF, excludeCiphers.split(",")); conn.setSSLSocketFactory(testPreferredCipherSSLSocketF); assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty()); try { InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyBytes(in, out, 1024); fail("No Ciphers in common, SSLHandshake must fail."); } catch (SSLHandshakeException ex) { LOG.info("No Ciphers in common, expected succesful test result.", ex); } }
From source file:org.apache.hadoop.http.TestSSLHttpServer.java
/** Test that verified that additionally included cipher * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working * TLS connection from client to server disabled for all other common ciphers. *///from w w w . j a va 2s.c o m @Test public void testOneEnabledCiphers() throws Exception { URL url = new URL(baseUrl, "/echo?a=b&c=d"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory(); PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory( sslSocketF, oneEnabledCiphers.split(",")); conn.setSSLSocketFactory(testPreferredCipherSSLSocketF); assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty()); try { InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyBytes(in, out, 1024); assertEquals(out.toString(), "a:b\nc:d\n"); LOG.info("Atleast one additional enabled cipher than excluded ciphers," + " expected successful test result."); } catch (SSLHandshakeException ex) { fail("Atleast one additional cipher available for successful handshake." + " Unexpected test failure: " + ex); } }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpApiConnection.java
/** * Connects to the back end system.// ww w . java 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:org.apache.hadoop.http.TestSSLHttpServer.java
/** Test verifies that mutually exclusive server's disabled cipher suites and * client's enabled cipher suites can successfully establish TLS connection. *//*from ww w.j a v a2s.c o m*/ @Test public void testExclusiveEnabledCiphers() throws Exception { URL url = new URL(baseUrl, "/echo?a=b&c=d"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory(); PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory( sslSocketF, exclusiveEnabledCiphers.split(",")); conn.setSSLSocketFactory(testPreferredCipherSSLSocketF); assertFalse("excludedCipher list is empty", exclusiveEnabledCiphers.isEmpty()); try { InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyBytes(in, out, 1024); assertEquals(out.toString(), "a:b\nc:d\n"); LOG.info("Atleast one additional enabled cipher than excluded ciphers," + " expected successful test result."); } catch (SSLHandshakeException ex) { fail("Atleast one additional cipher available for successful handshake." + " Unexpected test failure: " + ex); } }
From source file:org.getobjects.appserver.core.WOHTTPConnection.java
/** * (GETobjects extension):/* ww w . j a v a2 s . co m*/ * Called, whenever a new urlConnection is setup and only if it's a * HttpsURLConnection. * * This method is called in addition to * setupHttpURLConnection() and should contain refinement necessary for * SSL purposes, only. * * Subclasses may override or extend the steps taken. */ protected void setupHttpsURLConnection(HttpsURLConnection _conn) { _conn.setHostnameVerifier(this); if (this.allowInsecureSSL) { try { _conn.setSSLSocketFactory(new GullibleSSLSocketFactory(null)); } catch (GeneralSecurityException e) { e.printStackTrace(); } } }
From source file:org.apache.tez.runtime.library.shuffle.common.Fetcher.java
protected HttpURLConnection openConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (sslShuffle) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; try {//from w w w . ja v a 2s . co m httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory()); } catch (GeneralSecurityException ex) { throw new IOException(ex); } httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier()); } return conn; }