What is the URL.getQuery() method in Java?
The getQuery() method of the URL class can be used to get the query or parameter of a specified URL.
The image below shows the different parts of a URL.
The
URLclass is present in thejava.netpackage.
Syntax
The syntax of the getQuery() method is shown below.
public String getQuery()
Parameters
The getQuery() method doesn’t take any parameters.
Return value
The return type of the getQuery() method is string. If the URL doesn’t have any query then null is returned.
Code
The code below shows how to use the getQuery() method in Java.
import java.net.URL;class GetQueryExample {public static void main( String args[] ) {try {URL url= new URL("https:// www.educative.io?userid=123&lang=en");//Get QueryString query=url.getQuery();System.out.println("The URL is : "+url);System.out.println("\nReference or anchor is : "+ query);} catch (Exception e) {System.out.println(e);}}}
Explanation
In the code above:
- Line creates a URL object.
URL url= new URL("https:// www.educative.io?userid=123&lang=en");
- In line , the
getQuery()method gets the query segment of the URL object.
String query=url.getQuery();
- Finally, the URL and its query segment are printed in lines and .