Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daubac402/3448f04766a8ea27d30858579c740cb7 to your computer and use it in GitHub Desktop.
Save daubac402/3448f04766a8ea27d30858579c740cb7 to your computer and use it in GitHub Desktop.
Create a self-issued HTTPS certificate for your site for testing (for eg: localhost)

Create a self-issued HTTPS certificate for your site for testing (for eg: localhost)

Create the certificate (Output: public key cert + private key)

brew install mkcert
 
# First time
# If you want to add to Java as well, need to go to IntelliJ > Choose your project on the left side > F4 to open Project Structure > Project > SDK > Edit > Get the PATH to setup JAVA_HOME
# Eg: Mine is: /Users/your_name/Library/Java/JavaVirtualMachines/corretto-19.0.2/Contents/Home
# Add "nss" and separates with comma to install to Firefox browser Trust Store.
export JAVA_HOME=/Users/your_name/Library/Java/JavaVirtualMachines/corretto-19.0.2/Contents/Home
export TRUST_STORES=system,java
mkcert -install
 
# Create 2 files for your domain (eg: localhost): cert: localhost.pem and key: localhost-key.pem. Use these files to start your site with HTTPS
mkcert your_url_for_me_it_is_localhost

Export Mkcert's CA root cert on MacOS

You need to add this CA root cert to a Https client's trusted store (that you want to connect to your site)

  1. Enter "Keychain Access"
  2. Left panel, choose "System"
  3. Right panel's tab, choose "Certificates"
  4. Right click on "mkcert" cert > Export ..., name it as for eg: rootCA.pem

Add this Mkcert's CA root cert to JAVA_HOME's trusted stores at client

I have a Kubernetes pod that is running Java, and I want to connect to my site

# Get inside the server or pod
 
# Know JAVA_HOME location
java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'
# Assume it returns /usr/lib/jvm/java-17-openjdk/
 
# Copy the above rootCA.pem to somewhere, for eg: /home/your_name/rootCA.pem
 
# Import the CA root
echo yes | keytool -import -alias mkcert-root-ca1 -keystore /usr/lib/jvm/java-17-openjdk/lib/security/cacerts -file /home/your_name/rootCA.pem -storepass changeit

Test the connection from JVM to the HTTPS mock server

# Get inside the server or pod
 
# Create "TestHttpsConnection.java"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestHttpsConnection {
    public static void main(String[] args) {
        String urlString = "https://your_url_need_to_check_here"; // The url need to check
        try {
            // 1. Create a URL object
            URL url = new URL(urlString);
            // 2. Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. Set the request method (GET is default for curl)
            connection.setRequestMethod("GET");
            // Optional: Set a User-Agent header (good practice)
            connection.setRequestProperty("User-Agent", "Java/JVM-CurlLikeTest");
            // 4. Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 5. Read the response content (if successful)
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                System.out.println("Response Body (first 200 chars):");
                System.out.println(content.substring(0, Math.min(content.length(), 200)) + "..."); // Print a snippet
            } else {
                System.out.println("Error: Could not connect or received non-200 response.");
                System.out.println("Response Message: " + connection.getResponseMessage());
            }
            // 6. Disconnect
            connection.disconnect();
        } catch (Exception e) {
            System.err.println("An error occurred during the HTTP request:");
            e.printStackTrace();
        }
    }
}
 
# Build and Execute
javac TestHttpsConnection.java
java TestHttpsConnection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment