Example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory.

Prototype

public void setSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the <code>SSLSocketFactory</code> to be used when this instance creates sockets for secure https URL connections.

Usage

From source file:fr.bmartel.android.tictactoe.GameSingleton.java

private GameSingleton(Context context) {

    this.context = context.getApplicationContext();
    this.executor = Executors.newFixedThreadPool(1);

    //queue = Volley.newRequestQueue(context.getApplicationContext());
    HttpStack hurlStack = new HurlStack() {
        @Override/*  w  w w .  j a  v  a  2s  .com*/
        protected HttpURLConnection createConnection(URL url) throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            try {
                httpsURLConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
                httpsURLConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };
    queue = Volley.newRequestQueue(context, hurlStack);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    //load device id from shared preference
    DEVICE_ID = sharedPreferences.getString(RequestConstants.DEVICE_ID, "");
    deviceName = sharedPreferences.getString(RequestConstants.DEVICE_NAME, RequestConstants.DEFAULT_USERNAME);

    if (DEVICE_ID.equals("")) {
        //register deviceId in shared preference
        SharedPreferences.Editor editor = sharedPreferences.edit();
        DEVICE_ID = new RandomGen(DEVICE_ID_SIZE).nextString();
        editor.putString(RequestConstants.DEVICE_ID, DEVICE_ID);
        editor.commit();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/connect",
            RequestBuilder.buildConnectionRequest(DEVICE_ID, deviceName), new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "response received connect : " + response.toString());
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    error.printStackTrace();
                }
            });
    jsObjRequest.setShouldCache(false);

    queue.add(jsObjRequest);

    Log.i(TAG, "device id " + DEVICE_ID + " initialized");

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(context, RegistrationIntentService.class);
        context.startService(intent);
    }
}

From source file:org.forgerock.maven.plugins.LinkTester.java

private void checkUrl(String path, String docUrl) {
    if (shouldSkipUrl(docUrl)) {
        debug("Skipping " + docUrl + " since it matches a skipUrlPattern");
        return;/*from w w  w. j av a  2  s. co  m*/
    }
    if (tested.contains(docUrl)) {
        if (failedUrls.containsValue(docUrl)) {
            failedUrls.put(path, docUrl);
        }
        return;
    }
    debug("Checking " + docUrl + " from file: " + path);
    try {
        URL url = new URL(docUrl);
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) urlConn;
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
                httpsConn.setHostnameVerifier(new TrustAllHostnameVerifier());
                httpsConn.setSSLSocketFactory(TRUST_ALL_SOCKET_FACTORY);
            }

            conn.setConnectTimeout(1000);
            //if we don't get anything back within 15 seconds it is safe to assume that something is really wrong
            //with that site..
            conn.setReadTimeout(15000);
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400) {
                warn(docUrl + ": received unexpected response code: " + responseCode);
                failedUrls.put(path, docUrl);
            }
        }
    } catch (SocketTimeoutException ste) {
        warn(docUrl + ": " + ste.getClass().getName() + " " + ste.getMessage());
        timedOutUrls.put(path, docUrl);
    } catch (Exception ex) {
        warn(docUrl + ": " + ex.getClass().getName() + " " + ex.getMessage());
        failedUrls.put(path, docUrl);
    }
    tested.add(docUrl);
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

/**
 * Sets a ssl socket factory that sets a filtered list of ciphers based on
 * the #excludedSSLCipherRegex to the given connection.
 * /*from  w  ww  . jav  a  2  s .  c om*/
 * @param sslContext
 * 
 * @param sslContext
 *            the ssl context that shall be used
 * @param url
 *            the url we are connecting to
 * @param connection
 *            the connection that the cipher filter shall be applied to
 */
protected SSLContext setFilteredCiphers(String excludedSSLCipherRegex, SSLContext sslContext,
        HttpsURLConnection connection) {
    if (excludedSSLCipherRegex != null) {
        connection.setSSLSocketFactory(new EnabledCiphersSSLSocketFactory(
                SSLUtils.filterCiphers(excludedSSLCipherRegex, getSupportedCiphers(sslContext)),
                sslContext.getSocketFactory()));
    }
    return sslContext;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {//  ww  w .  ja  va2 s.  c o  m
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code HttpsURLConnection} from the given
 * {@code context} and {@code hostnameVerifier}.
 * /* w w w .  j  a  v a 2 s  .co  m*/
 * @param context
 *            the TrustManagerFactory to get the SSLContext
 * @return the new {@code HttpsURLConnection} instance.
 * @throws IOException
 *             if an error occurs while opening the connection.
 */
private HttpsURLConnection getURLConnection(SSLContext context, HostnameVerifier hostnameVerifier)
        throws IOException {

    URL url = new URL("https://10.0.2.2/mycode/digitalSig.php");

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setConnectTimeout(3000);
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setHostnameVerifier(hostnameVerifier);

    return urlConnection;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) {
    SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con = null;
    try {/*from   www .  j a  v a 2 s  . c om*/
        con = (HttpsURLConnection) url.openConnection();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
    con.setSSLSocketFactory(sslFactory);
    try {
        con.setRequestMethod(REQUEST_METHOD_GET);
    } catch (ProtocolException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }

    con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION);

    InputStream responseStream = null;
    try {
        responseStream = (InputStream) con.getContent();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }

    return responseStream;
}

From source file:org.apache.tez.engine.common.shuffle.impl.Fetcher.java

@VisibleForTesting
protected HttpURLConnection openConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (sslShuffle) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {//www. java  2  s .c  om
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    return conn;
}

From source file:org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl.java

private ConnectionConfigurator initSslConnConfigurator(final int timeout, Configuration conf)
        throws IOException, GeneralSecurityException {
    final SSLSocketFactory sf;
    final HostnameVerifier hv;

    sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
    sslFactory.init();/* ww  w . j a  v  a2  s .com*/
    sf = sslFactory.createSSLSocketFactory();
    hv = sslFactory.getHostnameVerifier();

    return new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection c = (HttpsURLConnection) conn;
                c.setSSLSocketFactory(sf);
                c.setHostnameVerifier(hv);
            }
            setTimeouts(conn, timeout);
            return conn;
        }
    };
}

From source file:org.comixwall.pffw.GraphsBase.java

/**
 * Run the controller task.//w w  w.j a  va  2s .com
 * We fetch the graphs using secure http, or fall back to plain http if secure connection fails.
 * <p>
 * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate
 * and not reject the hostname.
 *
 * @return True on success, false on failure.
 */
@Override
public boolean executeTask() {
    Boolean retval = true;
    try {
        String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight);

        JSONArray jsonArray = new JSONArray(output);
        mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString());

        Iterator<String> it = mGraphsJsonObject.keys();
        while (it.hasNext()) {
            String title = it.next();
            String file = mGraphsJsonObject.getString(title);

            try {
                InputStream stream = null;

                try {
                    String outputGraph = controller.execute("symon", "GetGraph", file);
                    String base64Graph = new JSONArray(outputGraph).get(0).toString();
                    stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warning("SSH graph connection exception: " + e.toString());
                }

                // Try secure http if ssh fails
                if (stream == null) {
                    // 1540861800_404e00f4044d07242a77f802e457f774
                    String hash = file.substring(file.indexOf('_') + 1);

                    try {
                        // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found.
                        // So we should trust the PFFW server crt and hostname
                        URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection();

                        // Tell the URLConnection to use a SocketFactory from our SSLContext
                        secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory());

                        // Install the PFFW host verifier
                        secureUrlConn.setHostnameVerifier(hostnameVerifier);

                        logger.finest("Using secure http: " + secureUrl.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        secureUrlConn.setConnectTimeout(5000);
                        secureUrlConn.setReadTimeout(5000);
                        logger.finest("Secure URL connection timeout values: "
                                + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout());

                        stream = secureUrlConn.getInputStream();

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warning("Secure URL connection exception: " + e.toString());
                    }

                    // Try plain http if secure http fails
                    if (stream == null) {
                        // ATTENTION: Don't use try-catch here, catch in the outer exception handling
                        URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection();

                        logger.finest("Using plain http: " + plainUrlConn.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        plainUrlConn.setConnectTimeout(5000);
                        plainUrlConn.setReadTimeout(5000);
                        logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout()
                                + ", " + plainUrlConn.getReadTimeout());

                        stream = plainUrlConn.getInputStream();
                    }
                }

                Bitmap bmp = BitmapFactory.decodeStream(stream);
                setBitmap(title, bmp);

            } catch (Exception e) {
                // We are especially interested in SocketTimeoutException, but catch all
                e.printStackTrace();
                logger.info("GraphsBase doInBackground exception: " + e.toString());
                // We should break out of while loop on exception, because all conn attempts have failed
                break;
            }
        }

        output = controller.execute("pf", "GetReloadRate");

        int timeout = Integer.parseInt(new JSONArray(output).get(0).toString());
        mRefreshTimeout = timeout < 10 ? 10 : timeout;

    } catch (Exception e) {
        e.printStackTrace();
        logger.warning("doInBackground exception: " + e.toString());
        retval = false;
    }
    return retval;
}

From source file:org.kontalk.client.ClientHTTPConnection.java

private void setupClient(HttpsURLConnection conn, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoInput(true);/*from ww  w.jav  a2 s . c o  m*/
    conn.setSSLSocketFactory(setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
}