To get the string representation of a URL
object in Java, you can use the toString
method of the URL
class. This method returns a string representation of the URL
object, including the protocol, host, port, path, and query string (if any).
Here is an example of how to use the toString
method to get the string representation of a URL
object:
URL url = new URL("https://www.example.com/path/to/resource?param1=value1¶m2=value2"); String urlString = url.toString(); System.out.println(urlString); // prints "https://www.example.com/path/to/resource?param1=value1¶m2=value2"
You can also use the getProtocol
, getHost
, getPort
, getPath
, and getQuery
methods of the URL
class to get the individual components of the URL
object as strings. For example:
String protocol = url.getProtocol(); // "https" String host = url.getHost(); // "www.example.com" int port = url.getPort(); // -1 (default port for https) String path = url.getPath(); // "/path/to/resource" String query = url.getQuery(); // "param1=value1¶m2=value2"