Search in sources :

Example 46 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project openhab1-addons by openhab.

the class OpenWebIfCommunicator method executeRequest.

/**
     * Executes the http request and parses the returned stream.
     */
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);
        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);
        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);
            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}
Also used : AllowAllHostnameVerifier(org.openhab.action.openwebif.internal.impl.ssl.AllowAllHostnameVerifier) JAXBException(javax.xml.bind.JAXBException) GeneralSecurityException(java.security.GeneralSecurityException) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) HttpURLConnection(java.net.HttpURLConnection) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) Unmarshaller(javax.xml.bind.Unmarshaller) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 47 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project okhttp by square.

the class ResponseCacheTest method cacheReturnsInsecureResponseForSecureRequest.

@Test
public void cacheReturnsInsecureResponseForSecureRequest() throws IOException {
    assumeFalse(getPlatform().equals("jdk9"));
    server.useHttps(sslClient.socketFactory, false);
    server.enqueue(new MockResponse().setBody("ABC"));
    server.enqueue(new MockResponse().setBody("DEF"));
    AndroidInternal.setResponseCache(urlFactory, new InsecureResponseCache(cache));
    HttpsURLConnection connection1 = (HttpsURLConnection) openConnection(server.url("/").url());
    connection1.setSSLSocketFactory(sslClient.socketFactory);
    connection1.setHostnameVerifier(hostnameVerifier);
    assertEquals("ABC", readAscii(connection1));
    // Not cached!
    HttpsURLConnection connection2 = (HttpsURLConnection) openConnection(server.url("/").url());
    connection2.setSSLSocketFactory(sslClient.socketFactory);
    connection2.setHostnameVerifier(hostnameVerifier);
    assertEquals("DEF", readAscii(connection2));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 48 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project okhttp by square.

the class CacheAdapterTest method put_httpsGet.

@Test
public void put_httpsGet() throws Exception {
    final URL serverUrl = configureHttpsServer(new MockResponse());
    assertEquals("https", serverUrl.getProtocol());
    ResponseCache responseCache = new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            try {
                assertTrue(connection instanceof HttpsURLConnection);
                assertEquals(toUri(serverUrl), uri);
                assertEquals(serverUrl, connection.getURL());
                HttpsURLConnection cacheHttpsUrlConnection = (HttpsURLConnection) connection;
                HttpsURLConnection realHttpsUrlConnection = (HttpsURLConnection) CacheAdapterTest.this.connection;
                assertEquals(realHttpsUrlConnection.getCipherSuite(), cacheHttpsUrlConnection.getCipherSuite());
                assertEquals(realHttpsUrlConnection.getPeerPrincipal(), cacheHttpsUrlConnection.getPeerPrincipal());
                assertArrayEquals(realHttpsUrlConnection.getLocalCertificates(), cacheHttpsUrlConnection.getLocalCertificates());
                assertArrayEquals(realHttpsUrlConnection.getServerCertificates(), cacheHttpsUrlConnection.getServerCertificates());
                assertEquals(realHttpsUrlConnection.getLocalPrincipal(), cacheHttpsUrlConnection.getLocalPrincipal());
                return null;
            } catch (Throwable t) {
                throw new IOException("unexpected cache failure", t);
            }
        }
    };
    setInternalCache(new CacheAdapter(responseCache));
    client = client.newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build();
    connection = new OkUrlFactory(client).open(serverUrl);
    executeGet(connection);
}
Also used : AbstractResponseCache(okhttp3.AbstractResponseCache) OkUrlFactory(okhttp3.OkUrlFactory) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) ResponseCache(java.net.ResponseCache) AbstractResponseCache(okhttp3.AbstractResponseCache) URI(java.net.URI) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 49 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project okhttp by square.

the class JavaApiConverterTest method createJavaUrlConnection_https_extraHttpsMethods.

@Test
public void createJavaUrlConnection_https_extraHttpsMethods() throws Exception {
    Request okRequest = createArbitraryOkRequest().newBuilder().get().url("https://secure/request").build();
    Handshake handshake = Handshake.get(null, CipherSuite.TLS_RSA_WITH_NULL_MD5, Arrays.<Certificate>asList(SERVER_CERT), Arrays.<Certificate>asList(LOCAL_CERT));
    Response okResponse = createArbitraryOkResponse(okRequest).newBuilder().handshake(handshake).build();
    HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) JavaApiConverter.createJavaUrlConnectionForCachePut(okResponse);
    assertEquals("SSL_RSA_WITH_NULL_MD5", httpsUrlConnection.getCipherSuite());
    assertEquals(SERVER_CERT.getSubjectX500Principal(), httpsUrlConnection.getPeerPrincipal());
    assertArrayEquals(new Certificate[] { LOCAL_CERT }, httpsUrlConnection.getLocalCertificates());
    assertArrayEquals(new Certificate[] { SERVER_CERT }, httpsUrlConnection.getServerCertificates());
    assertEquals(LOCAL_CERT.getSubjectX500Principal(), httpsUrlConnection.getLocalPrincipal());
}
Also used : CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) Request(okhttp3.Request) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Handshake(okhttp3.Handshake) Test(org.junit.Test)

Example 50 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project okhttp by square.

the class URLConnectionTest method testNoSslFallback.

@Test
public void testNoSslFallback() throws Exception {
    server.useHttps(sslClient.socketFactory, false);
    server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
    server.enqueue(new MockResponse().setBody("Response that would have needed fallbacks"));
    HttpsURLConnection connection = (HttpsURLConnection) server.url("/").url().openConnection();
    connection.setSSLSocketFactory(sslClient.socketFactory);
    try {
        connection.getInputStream();
        fail();
    } catch (SSLProtocolException expected) {
    // RI response to the FAIL_HANDSHAKE
    } catch (SSLHandshakeException expected) {
    // Android's response to the FAIL_HANDSHAKE
    }
}
Also used : SSLProtocolException(javax.net.ssl.SSLProtocolException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)522 URL (java.net.URL)310 IOException (java.io.IOException)177 HttpURLConnection (java.net.HttpURLConnection)128 InputStreamReader (java.io.InputStreamReader)93 InputStream (java.io.InputStream)89 Test (org.junit.Test)83 BufferedReader (java.io.BufferedReader)78 SSLContext (javax.net.ssl.SSLContext)70 OutputStream (java.io.OutputStream)54 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 MalformedURLException (java.net.MalformedURLException)48 URLConnection (java.net.URLConnection)47 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)46 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 HashMap (java.util.HashMap)34 DataOutputStream (java.io.DataOutputStream)32 KeyManagementException (java.security.KeyManagementException)32 JSONObject (org.json.JSONObject)29