What is the URL.getProtocol method in Java?
The getProtocol method of the URL class can be used to get the protocol (scheme) of the URL.
Syntax
public String getProtocol()
This method doesn’t take any arguments. The return type of this method is a string.
The
URLclass is present in thejava.netpackage.
In the image above, the part labeled with the scheme denotes the protocol of the URL.
Code
The code below uses the getProtocol method.
import java.net.URL;class GetRefExample {public static void main( String args[] ) {try {URL url= new URL("https://www.educative.io");//Get ProtocolString protocol=url.getProtocol();System.out.println("The URL is : "+url);System.out.println("The protocol is : "+protocol);} catch (Exception e) {System.out.println(e);}}}
Explanation
In the code above:
- On line 6, we created a
URLobject.
URL url= new URL("https://www.educative.io");
- On line 8, we used the
getProtocolmethod to get the protocol of theURLobject.
String protocol=url.getProtocol();
- On lines 9 and 10, we printed the
urlandprotocolof theURL.