Add query parameters Apache HttpClient
Suppose you want to send request to a URL with below format
https://app-url?param1=value1¶m2=value2¶m3=value3
Here,
param1, param2 and param3 are called Query parameters or Request parameters.
In this article, we will look at adding query parameters to a request URL in Apache HttpClient library in java.
If you do know how to send an HTTP request with HttpClient, refer this article.
[the_ad id=”651″]
URIBuilder
Apache HttpClient provides a URIBuilder
class which accepts a base URL as constructor argument.
For adding query parameters, it provides addParameter()
method, which takes two string arguments representing parameter name and value.
After the parameters are added to the URIBuilder
, call its build()
method to create an object of URI
class.
This URI
object is provided to the request using its setURI()
method.
URIBuilder
uses builder design pattern to construct an object of URI
.Example,
HttpPost post = new HttpPost("https://app-url"); URI uriBuilder = new URIBuilder(post.getURI()). addParameter("id", "10"). addParameter("name", "abc").build(); post.setURI(uriBuilder);
If you look at the logs, then you would see below line
20:16:54.250 [main] DEBUG org.apache.http.headers – http-outgoing-0 << Location: https://app-url?id=10&name=abc
which shows that it has successfully added query parameters to the URL.
Note that in above example, base URL for URIBuilder
is taken from request object using its getURI()
method.
But, we can also set the base URL directly in the URIBuilder
constructor as shown below
HttpPost post = new HttpPost(); URI uriBuilder = new URIBuilder("https://app-url"). addParameter("id", "10"). addParameter("name", "abc").build(); post.setURI(uriBuilder);
This also has the same result.
This method is applicable to both GET and POST request objects of HttpClient.
Adding all parameters
URIBuilder
provides an option to add multiple query parameters at once, instead of calling addParameter()
multiple times.
It has an addParameters()
method which takes a list of NameValuePair
objects. Example,
HttpPost post = new HttpPost("https://app-url"); // define a list List<NameValuePair> parameters = new ArrayList<>(); // add new parameters parameters.add(new BasicNameValuePair("id", "10")); parameters.add(new BasicNameValuePair("name", "abc")); URI uriBuilder = new URIBuilder(post.getURI()). addParameters(parameters). build(); post.setURI(uriBuilder);
NameValuePair
is an interface, so we create object of BasicNameValuePair
, which implements it.
[the_ad id=”656″]