I'm using apache URIBuilder to build a query string for a GET method of a Rest service.
@RequestMapping(value="/remote")
public Return getTest(Ordine ordine) throws Exception{
...
}
This is the input object:
public class Ordine{
private List<String> codici;
//..get...set..
}
I cannot understand how to set this string list as query params.
I tried to set param twice:
URIBuilder builder = new URIBuilder()
.setHost("localhost")
.setPort(8080)
.setScheme("http")
.setPath("/remote")
.setParameter("codici", codicilist.get(0))
.setParameter("codici", codicilist.get(1));
But the first param it will be overwrite from the second. Then I tried to append [] in the param name:
URIBuilder builder = new URIBuilder()
.setHost("localhost")
.setPort(8080)
.setScheme("http")
.setPath("/remote")
.setParameter("codici[]", codicilist.get(0))
.setParameter("codici[]", codicilist.get(1));
But it is simply sent with name "codici[]" and the first param is overwritten. Then I tried a comma separated values:
URIBuilder builder = new URIBuilder()
.setHost("localhost")
.setPort(8080)
.setScheme("http")
.setPath("/remote")
.setParameter("codici", String.join(",",codicilist));
But if fails... how can I set a list of param?
Query parameters allow you to pass optional parameters to a route such as pagination information. The key difference between query parameters and route parameters is that route parameters are essential to determining route, whereas query parameters are optional.
URI parameter (Path Param) is basically used to identify a specific resource or resources whereas Query Parameter is used to sort/filter those resources.
Query parameters are added to the URI in the usual way. Any parameter can be omitted. The client will pick sensible defaults when they are.
You can use addParameters method.
URIBuilder builder = new URIBuilder()
.setHost("localhost")
.setPort(8080)
.setScheme("http")
.setPath("/remote").addParameters(buildParamList())
Then get all codici
parameter values with a helper method which will build a list of NameValuePair
pairs.
private List<NameValuePair> buildParamList() {
List<NameValuePair> output = new ArrayList<>();
for (String string : codici) {
output.add(new BasicNameValuePair("codici", string));
}
return output;
}
So you'll get an output similar to http://localhost:8080/remote?codici=codici1&codici=codici2&codici=codici3 given that codici
list contains codici1
, codici2
, codici3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With