Pyth0n
Pyth0n

Reputation: 367

How can I easily use HTTPS (self-signed certificate) with JSoup?

In the university we must develop an android application, which grabs our marks from the website.

We use the JSoup Framework to grab and parse the HTML pages. The problem now is that our University uses a self-signed certificate for HTTPS connection, which is not trusted by a larger trusted CA.

I've seen for these frequently occurring problems, some general solutions, but they use a extended DefaultHttpClient with a own SSLSocketFactory. These solutions do not look very nice, is there a simple beautiful solution for this by usage of the JSoup Framework?

private LoginState connect(String username, String password) {
        try {
            if (isOnline()) {
                Log.i(TAG, "Sending POST.");

                Connection connection = Jsoup.connect(LOGIN_URL)
                        .data(USER_FIELD, username).data(PASS_FIELD, password)
                        .data(LOGIN_BUTTON, "Anmelden")
                        .data(LOGIN_TYPE, "login").data(PID, "2")
                        .timeout(DEFAULT_TIMEOUT);

                mDocument = connection.post();

                mCookies.putAll(connection.response().cookies());

                if (isConnected()) {
                    Log.i(TAG, "Login successful.");
                    setState(LoginState.LOGIN_SUCCESSFUL);
                } else {
                    Log.i(TAG, "Login failed.");
                    setState(LoginState.LOGIN_FAILED);
                }
            } else {
                Log.i(TAG, "No Internet Connection.");
                setState(LoginState.BAD_CONNECTION);
            }
        } catch (IOException ex) {
            Log.e(TAG, ex.getStackTrace().toString());
            setState(LoginState.BAD_CONNECTION);
        }

        return getState();
    }

Upvotes: 1

Views: 2842

Answers (1)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

Unless JSoup exposes some API that lets your pass your own trust store, no. If you have a rooted device you can install the university's cert to the trust store using this. If you have an Android 4.0 (ICS) device, there is an UI for installing trusted CA certificates. Another idea: use HttpClient to get the data, and then use JSoup for parsing only (that should be possible).

Upvotes: 1

Related Questions