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?
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