HTML Minifier Java Example

Check the example on how to use
Java
to minify a HTML hardcoded string and output to stdout:
import java.io.*;
import java.net.*;

class Minifier {
  public static void main(String[] args) {
    try {
      final URL url = new URL("https://www.toptal.com/developers/html-minifier/api/raw");
      var input = "<input type="text" />";
      
      final StringBuilder data = new StringBuilder();
      data.append(URLEncoder.encode("input", "UTF-8"));
      data.append('=');
      data.append(URLEncoder.encode(input, "UTF-8"));

      var bytes = data.toString().getBytes("UTF-8");

      final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("charset", "utf-8");
      conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));

      try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.write(bytes);
      }

      final int code = conn.getResponseCode();

      if (code == 200) {
        final BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
          System.out.print(inputLine);
        }
        in.close();

      } else {
        System.out.println("Oops");
      }
    } catch (Exception e) {
      System.out.println("Oops");
    }
  }
}
save the code to a file named
minify.java
and run the following command:
java minify.java

Output:

<input>