List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier
public void setHostnameVerifier(HostnameVerifier v)
HostnameVerifier
for this instance. From source file:org.talend.core.nexus.NexusServerUtils.java
/** * // w w w. jav a2 s.co m * DOC check if the repository exist or not * * @param nexusUrl * @param repositoryId * @param userName * @param password * @return */ public static boolean checkConnectionStatus(String nexusUrl, String repositoryId, final String userName, final String password) { if (StringUtils.isEmpty(nexusUrl)) { return false; } final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator(); if (userName != null && !"".equals(userName)) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } int status = -1; try { if (nexusUrl == null || "".equals(nexusUrl) || repositoryId == null || "".equals(repositoryId)) { return false; } String newUrl = nexusUrl; if (newUrl.endsWith(NexusConstants.SLASH)) { newUrl = newUrl.substring(0, newUrl.length() - 1); } String urlToCheck = newUrl + NexusConstants.CONTENT_REPOSITORIES + repositoryId; URL url = new URL(urlToCheck); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 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; } }); } IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE); int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000); urlConnection.setConnectTimeout(timeout); urlConnection.setReadTimeout(timeout); status = urlConnection.getResponseCode(); if (status == CONNECTION_OK) { return true; } } catch (Exception e) { ExceptionHandler.process(e); } finally { Authenticator.setDefault(defaultAuthenticator); } return false; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call for logging in// ww w.ja v a 2 s . c om * * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException { String response = ""; URL url = new URL(WebServiceAuthProvider.tokenURL()); trustAllHosts(); HttpsURLConnection connection = createSecureConnection(url); connection.setHostnameVerifier(DO_NOT_VERIFY); String authString = "mobile_android:secret"; String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } return response; }
From source file:com.daoke.mobileserver.test.TestHttps.java
public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;//from w ww. j a v a 2 s. c o m String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:jetbrains.buildServer.vmgr.agent.Utils.java
private static void configureAllowAll(HttpsURLConnection connection) { connection.setHostnameVerifier(new HostnameVerifier() { @Override/* ww w . ja v a2 s.co m*/ public boolean verify(String s, SSLSession sslSession) { return true; } }); try { connection.setSSLSocketFactory(getSocketFactory()); } catch (Exception e) { throw new RuntimeException("XTrust Failed to set SSL Socket factory", e); } }
From source file:info.guardianproject.netcipher.NetCipher.java
/** * Get a {@link HttpURLConnection} from a {@link URL}, and specify whether * it should use a more compatible, but less strong, suite of ciphers. * * @param url/* ww w . j a v a 2 s . c o m*/ * @param compatible * @return the {@code url} in an instance of {@link HttpURLConnection} * @throws IOException * @throws IllegalArgumentException if the proxy or TLS setup is incorrect */ public static HttpURLConnection getHttpURLConnection(URL url, boolean compatible) throws IOException { // .onion addresses only work via Tor, so force Tor for all of them Proxy proxy = NetCipher.proxy; if (OrbotHelper.isOnionAddress(url)) proxy = ORBOT_HTTP_PROXY; HttpURLConnection connection; if (proxy != null) { connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = ((HttpsURLConnection) connection); SSLSocketFactory tlsOnly = getTlsOnlySocketFactory(compatible); httpsConnection.setSSLSocketFactory(tlsOnly); if (Build.VERSION.SDK_INT < 16) { httpsConnection .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } } return connection; }
From source file:org.apache.atlas.security.SecureClientUtils.java
public static URLConnectionClientHandler getUrlConnectionClientHandler() { return new URLConnectionClientHandler(new HttpURLConnectionFactory() { @Override/*from w ww . j a v a2 s . com*/ public HttpURLConnection getHttpURLConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection instanceof HttpsURLConnection) { LOG.debug("Attempting to configure HTTPS connection using client " + "configuration"); final SSLFactory factory; final SSLSocketFactory sf; final HostnameVerifier hv; try { Configuration conf = new Configuration(); conf.addResource( conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES)); UserGroupInformation.setConfiguration(conf); HttpsURLConnection c = (HttpsURLConnection) connection; factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf); factory.init(); sf = factory.createSSLSocketFactory(); hv = factory.getHostnameVerifier(); c.setSSLSocketFactory(sf); c.setHostnameVerifier(hv); } catch (Exception e) { LOG.info("Unable to configure HTTPS connection from " + "configuration. Leveraging JDK properties."); } } return connection; } }); }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call for logging out// w w w .j a va 2 s . com * * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLogoutResponse(Context context) throws MalformedURLException, IOException, JSONException { // Refresh if necessary if (WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } URL url = new URL(urlForLogout(context)); HttpsURLConnection connection = createSecureConnection(url); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try { LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to the OCC web services * /*from ww w . j a va 2s . co m*/ * @param url * The url * @param isAuthorizedRequest * Whether this request requires the authorization token sending * @param httpMethod * method type (GET, PUT, POST, DELETE) * @param httpBody * Data to be sent in the body (Can be empty) * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException */ public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { // Refresh if necessary if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } // Make the connection and get the response OutputStream os; HttpURLConnection connection; if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) { url = url + "?" + encodePostBody(httpBody); } URL requestURL = new URL(addParameters(context, url)); if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) { trustAllHosts(); HttpsURLConnection https = createSecureConnection(requestURL); https.setHostnameVerifier(DO_NOT_VERIFY); if (isAuthorizedRequest) { String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); https.setRequestProperty("Authorization", authValue); } connection = https; } else { connection = createConnection(requestURL); } connection.setRequestMethod(httpMethod); if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) { connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); if (httpBody != null && !httpBody.isEmpty()) { os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } } response = ""; try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), context); response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) // There is an error other than a refresh error, so return the response return response; }
From source file:fr.ardeconnect.proxy.Service.java
static public HttpURLConnection getHUC(String address) { HttpURLConnection http = null; try {//from www .ja v a 2s.c o m URL url = new URL(address); if (url.getProtocol().equalsIgnoreCase("https")) { // only use trustAllHosts and DO_NOT_VERIFY in development // process trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); } } catch (Exception e) { e.printStackTrace(); } return http; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to get a new client credentials token, required for creating new account * // ww w . j a v a 2 s.com * @param url * @param clientCredentialsToken * @param httpMethod * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException * @throws JSONException */ public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url))); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); connection.setRequestMethod(httpMethod); connection.setDoOutput(true); connection.setDoInput(true); String authValue = "Bearer " + clientCredentialsToken; connection.setRequestProperty("Authorization", authValue); connection.connect(); if (!httpBody.isEmpty()) { OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }