Reputation: 21466
IN JAX-RS I need to iterate the (arbitrary) given query parameters in a request... but in their original order in the URI!
If I inject @Context UriInfo uriInfo
then I can use uriInfo.getQueryParameters()
to get a MultivaluedMap
of the query parameters, grouped by the query parameter name. But what if I care about the original order of all the query parameters? Is there a way to simply iterate the name/value pairs? Or must I extract them manually from uriInfo.getRequestUri()
?
If I'm stuck with manual extraction, is there some standard or well-maintained and updated library I can use for doing this?
Upvotes: 1
Views: 5535
Reputation: 31437
In case you're also using spring-web, you could parse the query parameters using UriComponentsBuilder
which preserves ordering:
String query = uriInfo.getRequestUri().getQuery();
UriComponents components = UriComponentsBuilder.newInstance().query(query).build();
// Ordered as they appeared in the query string
MultiValueMap<String, String> queryParams = components.getQueryParams();
Upvotes: 0
Reputation: 1276
Custom solution with apache HttpClient library:
public void process(@Context UriInfo uriInfo) {
String queryString = uriInfo.getRequestUri().getQuery()
//TODO: extract the charset from Content-Type header, if present
List<NameValuePair> queryParams = URLEncodedUtils.parse(queryString, "UTF-8")
for(NameValuePair param : queryParams) {
//do what you need
}
}
Upvotes: 1
Reputation: 1276
Query parameters are transformed to unordered Map (in jax-rs MultivaluedMap) in jax-rs and also in other REST/web frameworks. Also libraries, which are parsing the params are returning them in unordered way. I think for this special case you need to implement your own parsing solutions, which will put the params to LinkedHashMap. Look at existing custom parsing solutions here.
You can retrieve your query string with (mind that this is already decoded):
uriInfo.getRequestUri().getQuery()
However as you maybe know, your solution shouldn't rely on order of query parameters.
Upvotes: 1