List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier
public void setHostnameVerifier(HostnameVerifier v)
HostnameVerifier
for this instance. From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java
public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml, String soapAction) throws IOException, SOAPException { URI serviceLocation;//www. j a v a 2 s . co m try { serviceLocation = new URI(location); } catch (URISyntaxException e) { throw new IOException("Invalid uri for artifact resolve: " + location); } if (log.isDebugEnabled()) log.debug("serviceLocation..:" + serviceLocation); if (log.isDebugEnabled()) log.debug("SOAP Request: " + xml); HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection(); if (c instanceof HttpsURLConnection) { HttpsURLConnection sc = (HttpsURLConnection) c; if (ignoreCertPath) { sc.setSSLSocketFactory(new DummySSLSocketFactory()); sc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } } c.setAllowUserInteraction(false); c.setDoInput(true); c.setDoOutput(true); c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length); c.setRequestMethod("POST"); c.setReadTimeout(20000); c.setConnectTimeout(30000); addContentTypeHeader(xml, c); c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\""); if (username != null && password != null) { c.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES)); } OutputStream outputStream = c.getOutputStream(); IOUtils.write(xml, outputStream, "UTF-8"); outputStream.flush(); outputStream.close(); if (c.getResponseCode() == 200) { InputStream inputStream = c.getInputStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP response: " + result); XMLObject res = SAMLUtil.unmarshallElementFromString(result); Envelope envelope = (Envelope) res; if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) { log.warn( "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server"); throw new SOAPException(c.getResponseCode(), result); } return envelope; } else { log.debug("Response code: " + c.getResponseCode()); InputStream inputStream = c.getErrorStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP fault: " + result); throw new SOAPException(c.getResponseCode(), result); } }
From source file:org.talend.librariesmanager.utils.nexus.NexusDownloader.java
private HttpURLConnection getHttpURLConnection(String nexusUrl, String repositoryId, String relativePath, String userName, String password) throws Exception { String path = nexusUrl;//www.j a v a2 s .c om if (path.endsWith(NexusConstants.SLASH)) { path = path.substring(0, path.length() - 1); } path = path + NexusConstants.CONTENT_REPOSITORIES; path = path + repositoryId + NexusConstants.SLASH; URL url = new URL(path + relativePath); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (userName != null && !"".equals(userName)) { urlConnection.setRequestProperty("Authorization", //$NON-NLS-1$ "Basic " + Base64.encodeBase64((userName + ":" + password).getBytes()));//$NON-NLS-1$ } if (urlConnection instanceof HttpsURLConnection) { String userDir = Platform.getInstallLocation().getURL().getPath(); final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory(); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setSSLSocketFactory(socketFactory); httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(10000); return urlConnection; }
From source file:android.locationprivacy.algorithm.Webservice.java
@Override public Location obfuscate(Location location) { // We do it this way to run network connection in main thread. This // way is not the normal one and does not comply to best practices, // but the main thread must wait for the obfuscation service reply anyway. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);//from w ww . j a va2 s .co m final String HOST_ADDRESS = configuration.getString("host"); String username = configuration.getString("username"); String password = configuration.getString("secret_password"); Location newLoc = new Location(location); double lat = location.getLatitude(); double lon = location.getLongitude(); String urlString = HOST_ADDRESS; urlString += "?lat=" + lat; urlString += "&lon=" + lon; URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { Log.e(TAG, "Error: could not build URL"); Log.e(TAG, e.getMessage()); return null; } HttpsURLConnection connection = null; JSONObject json = null; InputStream is = null; try { connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); is = connection.getInputStream(); } catch (IOException e) { Log.e(TAG, "Error while connectiong to " + url.toString()); Log.e(TAG, e.getMessage()); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line = reader.readLine(); System.out.println("Line " + line); json = new JSONObject(line); newLoc.setLatitude(json.getDouble("lat")); newLoc.setLongitude(json.getDouble("lon")); } catch (IOException e) { Log.e(TAG, "Error: could not read from BufferedReader"); Log.e(TAG, e.getMessage()); return null; } catch (JSONException e) { Log.e(TAG, "Error: could not read from JSON"); Log.e(TAG, e.getMessage()); return null; } connection.disconnect(); return newLoc; }
From source file:com.alvexcore.share.ShareExtensionRegistry.java
public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes, String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion, String licenseId) throws Exception { // search for extension DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true);//ww w . j a v a2 s. co m xmlBuilder = xmlFact.newDocumentBuilder(); // build query Document queryXML = xmlBuilder.newDocument(); Element rootElement = queryXML.createElement("extension"); queryXML.appendChild(rootElement); Element el = queryXML.createElement("license-id"); el.appendChild(queryXML.createTextNode(licenseId)); rootElement.appendChild(el); el = queryXML.createElement("id"); el.appendChild(queryXML.createTextNode(extensionId)); rootElement.appendChild(el); el = queryXML.createElement("share-version"); el.appendChild(queryXML.createTextNode(shareVersion)); rootElement.appendChild(el); el = queryXML.createElement("repo-version"); el.appendChild(queryXML.createTextNode(repoVersion)); rootElement.appendChild(el); el = queryXML.createElement("share-id"); el.appendChild(queryXML.createTextNode(shareId)); rootElement.appendChild(el); el = queryXML.createElement("repo-id"); el.appendChild(queryXML.createTextNode(repoId)); rootElement.appendChild(el); el = queryXML.createElement("share-files"); rootElement.appendChild(el); for (String fileName : shareHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", shareHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } el = queryXML.createElement("repo-files"); rootElement.appendChild(el); for (String fileName : repoHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", repoHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } // query server try { URL url = new URL( "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // disable host verification conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML), new StreamResult(wr)); wr.close(); // get response Document responseXML = xmlBuilder.parse(conn.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); // get version String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) repoFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) shareFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE)) .getNodeValue(); return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion, shareLatestVersion, repoFiles, shareFiles, motd); } catch (Exception e) { return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "", new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), ""); } }
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 . j a 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: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; }/*ww w.ja va 2 s . c o m*/ 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:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Prepares a connection to the server./*from www . j av a 2s . co m*/ * @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:com.spotify.helios.client.DefaultRequestDispatcher.java
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity, final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy, final Identity identity) throws IOException { if (log.isTraceEnabled()) { log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(), Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length, Json.asPrettyStringUnchecked(entity)); } else {/* ww w. ja va2 s.co m*/ log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length); } final URLConnection urlConnection = ipUri.toURL().openConnection(); final HttpURLConnection connection = (HttpURLConnection) urlConnection; // We verify the TLS certificate against the original hostname since verifying against the // IP address will fail if (urlConnection instanceof HttpsURLConnection) { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); connection.setRequestProperty("Host", hostname); final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String ip, SSLSession sslSession) { final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1) : hostname; return new DefaultHostnameVerifier().verify(tHostname, sslSession); } }); if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) { final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user); httpsConnection.setSSLSocketFactory(factory); } } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS); connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS); for (Map.Entry<String, List<String>> header : headers.entrySet()) { for (final String value : header.getValue()) { connection.addRequestProperty(header.getKey(), value); } } if (entity.length > 0) { connection.setDoOutput(true); connection.getOutputStream().write(entity); } if (urlConnection instanceof HttpsURLConnection) { setRequestMethod(connection, method, true); } else { setRequestMethod(connection, method, false); } final int responseCode = connection.getResponseCode(); if (responseCode == HTTP_BAD_GATEWAY) { throw new ConnectException("502 Bad Gateway"); } return connection; }
From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java
/** * Sending the request and getting the response * @param Uri - request url/*from w w w .j a v a 2 s . com*/ * @param append - append request parameters * @throws IOException */ private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri; if (requestParameters != null && requestParameters.length() > 0) { if (append) { urlStr += "?" + requestParameters; } else { urlStr += requestParameters; } } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setReadTimeout(30000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } catch (IOException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:org.getobjects.appserver.core.WOHTTPConnection.java
/** * (GETobjects extension):/* ww w .ja v a 2 s. c o 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(); } } }