Search in sources :

Example 26 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project custom-cert-https by nelenkov.

the class MainActivity method defaultConnect.

private void defaultConnect() {
    new GetHtmlTask() {

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                if (setSystemPropCb.isChecked()) {
                    System.setProperty("javax.net.ssl.trustStore", localTrustStoreFile.getAbsolutePath());
                }
                URL url = new URL(SERVER_AUTH_URL);
                java.net.URLConnection conn = url.openConnection();
                HttpsURLConnection urlConnection = (HttpsURLConnection) conn;
                urlConnection.setUseCaches(false);
                urlConnection.setRequestProperty("Connection", "close");
                urlConnection.setConnectTimeout(TIMEOUT);
                urlConnection.setReadTimeout(TIMEOUT);
                try {
                    Log.d(TAG, "ClientSessionContext: " + SSLContext.getInstance("TLS").getClientSessionContext().getClass().getName());
                    Log.d(TAG, "SSLSocketFactory " + urlConnection.getSSLSocketFactory().getClass().getName());
                    urlConnection.connect();
                    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                        return urlConnection.getResponseMessage();
                    }
                    return readLines(urlConnection.getInputStream(), urlConnection.getContentEncoding());
                } finally {
                    urlConnection.disconnect();
                }
            } catch (Exception e) {
                Log.d(TAG, "Error: " + e.getMessage(), e);
                error = e;
                return null;
            } finally {
                if (trustStorePropDefault != null) {
                    System.setProperty("javax.net.ssl.trustStore", trustStorePropDefault);
                } else {
                    System.clearProperty("javax.net.ssl.trustStore");
                }
            }
        }
    }.execute();
}
Also used : URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 27 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project custom-cert-https by nelenkov.

the class MainActivity method urlConnConnect.

private void urlConnConnect() {
    new GetHtmlTask() {

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                boolean useClientAuth = useClientAuthCb.isChecked();
                SSLContext sslCtx = createSslContext(useClientAuth);
                URL url = new URL(useClientAuth ? CLIENT_AUTH_URL : SERVER_AUTH_URL);
                HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                urlConnection.setUseCaches(false);
                urlConnection.setRequestProperty("Connection", "close");
                urlConnection.setConnectTimeout(TIMEOUT);
                urlConnection.setReadTimeout(TIMEOUT);
                urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());
                HostnameVerifier verifier = urlConnection.getHostnameVerifier();
                Log.d(TAG, "hostname verifier: " + verifier.getClass().getName());
                try {
                    urlConnection.connect();
                    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                        return urlConnection.getResponseMessage();
                    }
                    return readLines(urlConnection.getInputStream(), urlConnection.getContentEncoding());
                } finally {
                    urlConnection.disconnect();
                }
            } catch (Exception e) {
                Log.d(TAG, "Error: " + e.getMessage(), e);
                error = e;
                return null;
            }
        }
    }.execute();
}
Also used : SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) HostnameVerifier(javax.net.ssl.HostnameVerifier) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier)

Example 28 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 29 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project scdl by passy.

the class HttpRequest method applyTrustManager.

/**
	 * Set up one or multiple trust managers for this connection. Does nothing
	 * if the current request is no SSL connection.
	 * 
	 * @param manager
	 * @return this instance.
	 */
public HttpRequest applyTrustManager(final TrustManager[] trustManagers) {
    if (!(connection instanceof HttpsURLConnection)) {
        return this;
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (final NoSuchAlgorithmException e) {
        // Again, should not happen if I didn't type it wrong.
        throw new IllegalArgumentException(e);
    }
    try {
        sslContext.init(null, trustManagers, null);
    } catch (final KeyManagementException e) {
        throw new IllegalStateException(e);
    }
    ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
    return this;
}
Also used : SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) KeyManagementException(java.security.KeyManagementException)

Example 30 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project httpclient by pixmob.

the class HttpRequestBuilder method execute.

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }
            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=").append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }
            if (!contentSet && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);
        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }
        if (cookies != null && !cookies.isEmpty() || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }
        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }
        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }
        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {
            if (content != null) {
                conn.setDoOutput(true);
                if (!contentSet) {
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
                } else if (contentType != null) {
                    conn.setRequestProperty("Content-Type", contentType);
                }
                conn.setFixedLengthStreamingMode(content.length);
                final OutputStream out = conn.getOutputStream();
                out.write(content);
                out.flush();
            } else {
                conn.setFixedLengthStreamingMode(0);
            }
        }
        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }
        conn.connect();
        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }
        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }
        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) GeneralSecurityException(java.security.GeneralSecurityException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpURLConnection(java.net.HttpURLConnection) SocketTimeoutException(java.net.SocketTimeoutException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)209 URL (java.net.URL)113 HttpURLConnection (java.net.HttpURLConnection)51 IOException (java.io.IOException)50 Test (org.junit.Test)39 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)29 InputStream (java.io.InputStream)27 HostnameVerifier (javax.net.ssl.HostnameVerifier)23 SSLContext (javax.net.ssl.SSLContext)23 OutputStream (java.io.OutputStream)20 MockResponse (com.google.mockwebserver.MockResponse)19 InputStreamReader (java.io.InputStreamReader)19 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)19 URLConnection (java.net.URLConnection)17 BufferedReader (java.io.BufferedReader)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 MalformedURLException (java.net.MalformedURLException)13 Proxy (java.net.Proxy)13 MockResponse (okhttp3.mockwebserver.MockResponse)13