How to remove URL prefix (http://, ssh://, etc) in Java

Published
Updated

Simply pass the string into a URL constructor and then append getAuthority() to getPath() and the resulting string will not contain the protocol.

For example:

import java.net.MalformedURLException;
import java.net.URL;

public class URLExample {

    public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("https://www.google.com/example.do?test=123");
        System.out.println(url.getAuthority() + url.getPath());
        // prints www.google.com/example.do?test=123
    }
}