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.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code HttpsURLConnection} from the given
 * {@code context} and {@code hostnameVerifier}.
 * /*from   www.  j  av a  2s. c  o 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: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 a2 s. c o m*/
        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.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();/*from  w w w.  j  a v  a 2s.  co m*/
    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:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. // www.  j a  va2s. com
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:it.govpay.core.utils.client.BasicClient.java

private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl)
        throws ClientException {

    // Creazione Connessione
    int responseCode;
    HttpURLConnection connection = null;
    byte[] msg = null;
    GpContext ctx = GpThreadLocal.get();
    String urlString = url.toExternalForm();
    if (isAzioneInUrl) {
        if (!urlString.endsWith("/"))
            urlString = urlString.concat("/");
        try {/*w ww.  jav  a  2s.c o  m*/
            url = new URL(urlString.concat(azione));
        } catch (MalformedURLException e) {
            throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e);
        }
    }

    try {
        Message requestMsg = new Message();
        requestMsg.setType(MessageType.REQUEST_OUT);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        if (soap) {
            connection.setRequestProperty("SOAPAction", "\"" + azione + "\"");
            requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\""));
        }
        requestMsg.setContentType("text/xml");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestMethod("POST");

        // Imposta Contesto SSL se attivo
        if (sslContext != null) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
            httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
            HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled();
            httpsConn.setHostnameVerifier(disabilitato);
        }

        // Imposta l'autenticazione HTTP Basic se attiva
        if (ishttpBasicEnabled) {
            Base64 base = new Base64();
            String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes()));
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            requestMsg.addHeader(new Property("Authorization", "Basic " + encoding));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (soap) {
            SOAPUtils.writeMessage(body, header, baos);
        } else {
            JaxbUtils.marshal(body, baos);
        }

        ctx.getIntegrationCtx().setMsg(baos.toByteArray());
        invokeOutHandlers();

        if (log.getLevel().isMoreSpecificThan(Level.TRACE)) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getRequestProperties().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key));
            }
            sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg()));
            log.trace(sb.toString());
        }

        requestMsg.setContent(ctx.getIntegrationCtx().getMsg());

        ctx.getContext().getRequest().setOutDate(new Date());
        ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length));
        ctx.log(requestMsg);

        connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg());

    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        responseCode = connection.getResponseCode();
        ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode));

    } catch (Exception e) {
        throw new ClientException(e);
    }

    Message responseMsg = new Message();
    responseMsg.setType(MessageType.RESPONSE_IN);

    for (String key : connection.getHeaderFields().keySet()) {
        if (connection.getHeaderFields().get(key) != null) {
            if (key == null)
                responseMsg
                        .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0)));
            else if (connection.getHeaderFields().get(key).size() == 1)
                responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0)));
            else
                responseMsg.addHeader(
                        new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key))));
        }
    }

    try {
        if (responseCode < 300) {
            try {
                if (connection.getInputStream() == null) {
                    return null;
                }
                msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream())
                        : new byte[] {};
                if (msg.length > 0)
                    responseMsg.setContent(msg);
                return msg;
            } catch (Exception e) {
                throw new ClientException("Messaggio di risposta non valido", e);
            }
        } else {
            try {
                msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream())
                        : new byte[] {};
                responseMsg.setContent(msg);
            } catch (IOException e) {
                msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes();
            } finally {
                log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode
                        + "]\nRisposta: " + new String(msg));
            }

            throw new ClientException("Ricevuto [HTTP " + responseCode + "]");
        }
    } finally {
        if (responseMsg != null) {
            ctx.getContext().getResponse().setInDate(new Date());
            ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length);
            ctx.log(responseMsg);
        }

        if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null
                && connection.getHeaderFields() != null) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getHeaderFields().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getHeaderField(key));
            }
            sb.append("\n" + new String(msg));
            log.trace(sb.toString());
        }
    }

}

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

public String[] callGet(String stringUrl) {
    try {//from   ww  w .ja v  a2 s .co m

        // Setup connection
        URL url = new URL(stringUrl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        // 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;
            }
        });
        // printHttpsCert(conn);
        conn.connect();
        int code = conn.getResponseCode();

        if (code >= 200 && code < 300) {
            String result = IOUtils.toString(conn.getInputStream());
            conn.disconnect();
            return new String[] { code + "", result };
        } else {
            conn.disconnect();
            return new String[] { code + "", "Server returned " + code + " response code" };
        }

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

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private String getPEMCertificateFromServer(String host) {
    HttpsURLConnection connection = null;
    try {//from w  w  w .  j  a v  a  2  s .com
        URL url = new URL(host);

        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(hostnameVerifier);
        connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
        connection.connect();

        java.security.cert.Certificate[] cert = connection.getServerCertificates();
        connection.disconnect();

        byte[] by = ((X509Certificate) cert[0]).getEncoded();
        if (by.length != 0) {
            return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
        }
    } catch (MalformedURLException e) {
        if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
            logger.error("A MalformedURLException occurred: ", e);
        }
    } catch (IOException e) {
        short code = ConnectionManager.GENERAL_EXCEPTION;
        if (e instanceof java.net.ConnectException) {
            code = ConnectionManager.CONNECTION_EXCEPTION;
        } else if (e instanceof java.net.UnknownHostException) {
            code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
        }
        if (!informConnectionManager(code) || code == -1) {
            logger.error("An IOException occurred: ", e);
        }
    } catch (CertificateEncodingException e) {
        logger.error("A CertificateEncodingException occurred: ", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:org.apache.tez.runtime.library.shuffle.common.Fetcher.java

protected HttpURLConnection openConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (sslShuffle) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {//from  w  w  w.ja  va  2s.  c o m
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    return conn;
}

From source file:com.vuze.android.remote.AndroidUtils.java

private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) {
    try {//w w w  .j  ava  2  s .  c o m
        HttpURLConnection.setFollowRedirects(false);

        URL url = new URL(URLName);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection conHttps = (HttpsURLConnection) con;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                        new SecureRandom());
                conHttps.setSSLSocketFactory(ctx.getSocketFactory());
            }

            conHttps.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        con.setConnectTimeout(conTimeout);
        con.setReadTimeout(readTimeout);
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        if (DEBUG) {
            Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage());
        }
        return true;
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "isLive " + URLName, e);
        }
        return false;
    }
}

From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java

/**
 * Upload a file to the given URL//from   w  ww .j a  v a 2s.co m
 *
 * @param importUrl URL to be file upload
 * @param fileName  Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(importUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER,
            "Basic " + encodeCredentials(user, pass));
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder response = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        response.append(temp);
    }
    Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response);
}