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:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP request extractor//from ww  w .  j  a va 2  s . c o m
 *
 * @param urlToRead device URL
 * @return device type string
 * @throws IOException
 */
public static String getHTML(String urlToRead) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }

        conn.setRequestMethod("GET");
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP POST with basic auth/*from  ww w  .ja va 2 s.  c  o  m*/
 *
 * @param urlToRead device URL
 * @return http response message
 * @throws IOException
 */
public static String httpPost(String urlToRead, String username, String password) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        conn.setDoOutput(true);
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("x-dell-api-version", "2.0");
        conn.setRequestProperty("Authorization", encodeCredentials(username, password));
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setFixedLengthStreamingMode("{}".length());
        conn.getOutputStream().write("{}".getBytes(Charset.forName("UTF-8")));

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static Map<String, String> sendToServer(String epPostFix, Map<String, String> params, String option,
        Context context) throws IOException {
    String response = null;//from  w  ww .  j  av  a  2  s . c  o  m
    Map<String, String> response_params = new HashMap<String, String>();
    String endpoint = CommonUtilities.SERVER_URL + epPostFix;

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    String ipSaved = mainPref.getString("ip", "");

    if (ipSaved != null && ipSaved != "") {
        endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT
                + CommonUtilities.SERVER_APP_ENDPOINT + epPostFix;
    }

    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    HttpsURLConnection sConn = null;
    try {

        if (url.getProtocol().toLowerCase().equals("https")) {

            sConn = (HttpsURLConnection) url.openConnection();
            sConn = getTrustedConnection(context, sConn);
            sConn.setHostnameVerifier(WSO2MOBILE_HOST);
            conn = sConn;

        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod(option);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Connection", "close");
        // post the request
        int status = 0;
        Log.v("Check verb", option);
        if (!option.equals("DELETE")) {
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            status = conn.getResponseCode();
            Log.v("Response Status", status + "");
            InputStream inStream = conn.getInputStream();
            response = inputStreamAsString(inStream);
            response_params.put("response", response);
            Log.v("Response Message", response);
            response_params.put("status", String.valueOf(status));
        } else {
            status = Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL);
        }
        if (status != Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL)
                && status != Integer.valueOf(CommonUtilities.REGISTERATION_SUCCESSFUL)) {
            throw new IOException("Post failed with error code " + status);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response_params;
}

From source file:com.cloudera.nav.sdk.client.writer.MetadataWriterFactory.java

private HttpURLConnection openConnection(URL url) throws IOException {
    if (isSSL) {/* w w  w.j av  a 2 s. c o m*/
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(hostnameVerifier);
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        return conn;
    } else {
        return (HttpURLConnection) url.openConnection();
    }
}

From source file:org.apache.hadoop.gateway.hdfs.web.KnoxUrlConnectionFactory.java

private void configureConnectionHostnameVerifier(URLConnection connection) {
    if (!config.getBoolean("knox.webhdfs.verify.hostname", true)) {
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
        }//from www .j  a  v a  2  s . c  om
    }
}

From source file:org.bitrepository.protocol.http.HttpsFileExchange.java

/**
 * Method for opening a HTTP connection to the given URL.
 * TODO needs some SSL stuff??/*from  w  w w  . j  av a  2s. c  om*/
 * 
 * @param url The URL to open the connection to.
 * @return The HTTP connection to the given URL.
 */
@Override
protected HttpURLConnection getConnection(URL url) {
    try {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(hostnameVerifier);
        return connection;
    } catch (IOException e) {
        throw new CoordinationLayerException("Could not open the connection to the url '" + url + "'", e);
    }
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

static public HttpURLConnection getHUC(String address) {
    HttpURLConnection http = null;
    try {/*ww  w. jav  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.qpark.eip.core.spring.security.https.EipHttpsClientHttpRequestFactory.java

/**
 * @see org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(java.net.HttpURLConnection,
 *      java.lang.String)/*  w  w w  . j  av  a  2 s . c om*/
 */
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) {
    try {
        /* Setup HttpsURLConnection. */
        if (HttpsURLConnection.class.isInstance(connection)) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(this.x509TrustManager);
            TrustManager[] trustManagers = new TrustManager[] { this.x509TrustManager };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        super.prepareConnection(connection, httpMethod);
        /* Setup the basic Authentication. */
        if (HttpURLConnection.class.isInstance(connection) && this.userName != null) {
            HttpURLConnection httpsConnection = connection;
            httpsConnection.setRequestProperty("Authorization",
                    new StringBuffer(128).append("Basic ").append(this.base64UserNamePassword).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cn.cuizuoli.appranking.http.client.TrustClientHttpRequestFactory.java

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    if (StringUtils.equals(url.getProtocol(), "https")) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection urlConnection = (HttpsURLConnection) (proxy != null ? url.openConnection(proxy)
                : url.openConnection());
        urlConnection.setHostnameVerifier(DO_NOT_VERIFY);
        return urlConnection;
    } else {//from w  ww  .  j  a v  a  2  s  .co  m
        HttpURLConnection urlConnection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy)
                : url.openConnection());
        return urlConnection;
    }
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

private HttpsURLConnection createHttpUrlConnection(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new TrustAllHosts());
    conn.setSSLSocketFactory(TrustAllCerts.createInsecureSslContext().getSocketFactory());
    conn.setInstanceFollowRedirects(false);
    String credentials = TEST_USERNAME + ":" + TEST_PASSWORD;
    conn.setRequestProperty("Authorization",
            "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
    return conn;//from  w  ww  .  j av  a  2  s.  c o  m
}