Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

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

Introduction

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

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:org.jclouds.http.internal.JavaUrlHttpCommandExecutorService.java

@Override
protected HttpURLConnection convert(HttpRequest request) throws IOException {
    URL url = request.getEndpoint().toURL();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (relaxHostname && connection instanceof HttpsURLConnection) {
        HttpsURLConnection sslCon = (HttpsURLConnection) connection;
        sslCon.setHostnameVerifier(new LogToMapHostnameVerifier());
    }//from  www .  ja va 2 s .  c  o  m
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    // do not follow redirects since https redirects don't work properly
    // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be
    // <adriancole.s3int0.s3-external-3.amazonaws.com>
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(request.getMethod().toString());
    for (String header : request.getHeaders().keySet()) {
        for (String value : request.getHeaders().get(header)) {
            connection.setRequestProperty(header, value);

            if ("Transfer-Encoding".equals(header) && "chunked".equals(value)) {
                connection.setChunkedStreamingMode(8192);
            }
        }
    }
    connection.setRequestProperty(HttpHeaders.HOST, request.getEndpoint().getHost());
    if (request.getEntity() != null) {
        OutputStream out = connection.getOutputStream();
        try {
            if (request.getEntity() instanceof String) {
                OutputStreamWriter writer = new OutputStreamWriter(out);
                writer.write((String) request.getEntity());
                writer.close();
            } else if (request.getEntity() instanceof InputStream) {
                IOUtils.copy((InputStream) request.getEntity(), out);
            } else if (request.getEntity() instanceof File) {
                IOUtils.copy(new FileInputStream((File) request.getEntity()), out);
            } else if (request.getEntity() instanceof byte[]) {
                IOUtils.write((byte[]) request.getEntity(), out);
            } else {
                throw new UnsupportedOperationException(
                        "Content not supported " + request.getEntity().getClass());
            }
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0");
    }
    return connection;
}

From source file:edu.mayo.xsltserver.controller.XsltServerController.java

protected InputStream createInputStreamFromUrl(URL url) throws IOException {
    final URLConnection urlCon = url.openConnection();

    if (urlCon instanceof HttpsURLConnection) {
        HttpsURLConnection connection = (HttpsURLConnection) urlCon;
        connection.setHostnameVerifier(VERIFY_ALL_HOST_NAMES);
        connection.setSSLSocketFactory(sslSocketFactory);
    }// ww w. j  av a2s. c  om

    return urlCon.getInputStream();
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }//from  ww  w.j av a 2s .co m
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:org.wso2.iot.firealarm.access.api.AccessTokenClient.java

public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
        throws AccessTokenException {
    SSLContext ctx;/*from w  w  w  .j  a v  a  2s  . c o m*/
    String response = "";
    try {
        ctx = SSLContext.getInstance("TLS");

        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL(tokenURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        //System.out.println(conn.getResponseCode());
        conn.disconnect();

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(tokenURL);
        postMethod.addParameter(new NameValuePair("grant_type", grantType));
        postMethod.addParameter(new NameValuePair("username", username));
        postMethod.addParameter(new NameValuePair("password", password));
        postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

        postMethod.addRequestHeader("Authorization", "Basic " + appToken);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        httpClient.executeMethod(postMethod);

        response = postMethod.getResponseBodyAsString();
        log.info(response);
        JSONObject jsonObject = new JSONObject(response);

        AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
        accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
        accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
        accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
        accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

        return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {
        log.error(e.getMessage());
        throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

        return null;
    }

}

From source file:dk.netarkivet.common.distribute.HTTPSRemoteFileRegistry.java

/**
 * Open a connection to an URL in this registry. Thus opens SSL connections using the certificate above.
 *
 * @param url The URL to open connection to.
 * @return an open connection to the given url
 * @throws IOException If unable to open connection to the URL
 * @throws IOFailure If the connection is not a secure connection
 *//*w  w w .  ja v a 2  s.  c o  m*/
@Override
protected URLConnection openConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    if (!(connection instanceof HttpsURLConnection)) {
        throw new IOFailure("Not a secure URL to remote file: " + url);
    }
    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    httpsConnection.setHostnameVerifier(ACCEPTING_HOSTNAME_VERIFIER);
    return httpsConnection;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java

protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod,
        final long lastFetchTime) throws IOException {
    String method = GET_STR;/*from  www .j a  v  a2  s .  c  o m*/

    if (requestMethod != null) {
        method = requestMethod;
    }

    LOGGER.info(method + "ing: " + url + "; timeout is " + timeout);

    final URLConnection connection = new URL(url).openConnection();

    connection.setIfModifiedSince(lastFetchTime);

    if (timeout != 0) {
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
    }

    final HttpURLConnection http = (HttpURLConnection) connection;

    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;
        https.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
    }

    http.setInstanceFollowRedirects(false);
    http.setRequestMethod(method);
    http.setAllowUserInteraction(true);

    for (final String key : requestProps.keySet()) {
        http.addRequestProperty(key, requestProps.get(key));
    }

    if (method.equals(POST_STR) && data != null) {
        http.setDoOutput(true); // Triggers POST.

        try (final OutputStream output = http.getOutputStream()) {
            output.write(data.getBytes(UTF8_STR));
        }
    }

    connection.connect();

    return http;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java

@Override
public HootResult synchronousExecute(HootRequest request) {
    if (request.isCancelled()) {
        return request.getResult();
    }/*from  w ww  .j  a  va  2s.c om*/

    mStreamingMode = (request.getQueryParameters() == null && request.getData() == null
            && request.getMultipartEntity() == null) ? StreamingMode.CHUNKED : StreamingMode.FIXED;

    if (request.getStreamingMode() == HootRequest.STREAMING_MODE_FIXED) {
        mStreamingMode = StreamingMode.FIXED;
    }

    HttpURLConnection connection = null;
    try {
        String url = request.buildUri().toString();
        Log.v(TAG, "Executing [" + url + "]");
        connection = (HttpURLConnection) new URL(url).openConnection();
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(mSSLHostNameVerifier);
        }
        connection.setConnectTimeout(mTimeout);
        connection.setReadTimeout(mTimeout);
        synchronized (mConnectionMap) {
            mConnectionMap.put(request, connection);
        }

        setRequestMethod(request, connection);
        setRequestHeaders(request, connection);

        if (request.getMultipartEntity() != null) {
            setMultipartEntity(request, connection);
        } else if (request.getData() != null) {
            setRequestData(request, connection);
        }

        HootResult hootResult = request.getResult();
        hootResult.setResponseCode(connection.getResponseCode());
        Log.d(TAG, " - received response code [" + connection.getResponseCode() + "]");
        if (request.getResult().isSuccess()) {
            hootResult.setHeaders(connection.getHeaderFields());
            hootResult.setResponseStream(new BufferedInputStream(connection.getInputStream()));
        } else {
            hootResult.setResponseStream(new BufferedInputStream(connection.getErrorStream()));
        }
        request.deserializeResult();
    } catch (Exception e) {
        request.getResult().setException(e);
        e.printStackTrace();
    } finally {
        if (connection != null) {
            synchronized (mConnectionMap) {
                mConnectionMap.remove(request);
            }
            connection.disconnect();
            connection = null;
        }
    }
    return request.getResult();
}

From source file:com.LogicTree.app.Florida511.AudioDownloader.java

/**
 * @param Url// w w w.  j  av a  2  s .  c  o m
 * @param filename
 * @return
 */
private boolean downloadAudio(String Url, String filename) {

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient()
            : AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(Url);
    boolean succ = false;
    try {

        HttpURLConnection http = null;
        URL url = new URL(Url);
        if (url.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
        } else {
            http = (HttpURLConnection) url.openConnection();
        }
        InputStream stream = null;
        try {
            stream = http.getInputStream();
            createExternalStoragePrivateFile(filename, stream);
            succ = true;
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving audio from " + Url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + Url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving audio from " + Url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return succ;
}

From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

private HttpURLConnection getConnection(String urlString)
        throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {

    if (urlString.startsWith("https://")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString));
        connection.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }/*from  www .ja  va 2  s . co  m*/
        });
        return connection;

    } else if (urlString.contains("@")) {

        URL passedURL = new URL(urlString);
        String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@"));
        String userName = creds.substring(0, creds.indexOf(":"));
        String passWord = creds.substring(creds.indexOf(":") + 1, creds.length());
        String userPassword = userName + ":" + passWord;
        // TODO cambiar implementacin de Base64
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        // TODO soporta proxy?
        HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        return connection;

    } else {
        return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString));
    }
}