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
URL
class is present in thejava.net
package.
The syntax of the getQuery()
method is shown below.
public String getQuery()
The getQuery()
method doesn’t take any parameters.
The return type of the getQuery()
method is string
. If the URL doesn’t have any query then null
is returned.
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);}}}
In the code above:
URL url= new URL("https:// www.educative.io?userid=123&lang=en");
getQuery()
method gets the query segment of the URL object.String query=url.getQuery();