I am building a generic web service and need to grab all the query parameters into one string for later parsing. How can I do this?
            Asked
            
        
        
            Active
            
        
            Viewed 6.6k times
        
    3 Answers
170
            You can access a single param via @QueryParam("name") or all of the params via the context:
@POST
public Response postSomething(@QueryParam("name") String name, @Context UriInfo uriInfo, String content) {
     MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); 
     String nameParam = queryParams.getFirst("name");
}
The key is the @Context jax-rs annotation, which can be used to access:
UriInfo, Request, HttpHeaders, SecurityContext, Providers
 
    
    
        hisdrewness
        
- 7,599
- 2
- 21
- 28
- 
                    Can we use with GET ? – Nagappa L M Oct 16 '14 at 06:31
35
            
            
        The unparsed query part of the request URI can be obtained from the UriInfo object:
@GET
public Representation get(@Context UriInfo uriInfo) {
  String query = uriInfo.getRequestUri().getQuery();
  ...
}
 
    
    
        glerup
        
- 1,532
- 1
- 12
- 11
4
            
            
        Adding a bit more to the accepted answer. It is also possible to get all the query parameters in the following way without adding an additional parameter to the method which maybe useful when maintaining swagger documentation.
@Context
private UriInfo uriInfo;
@POST
public Response postSomething(@QueryParam("name") String name) {
     MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); 
     String nameParam = queryParams.getFirst("name");
}
 
    
    
        Janak
        
- 460
- 5
- 15
- 
                    While this works, i wouldn't recommend it. If you can keep code functional pure, you should try it - it's the better approach. – martyglaubitz Feb 20 '19 at 08:21
- 
                    1Although strictly correct, I'm using this approach with a superclass to automatically log parameters, and it works very nicely. Much cleaner than having to pass the parameters with each request. Sometimes functional purity needs to just look the other way for a few seconds while pragmatic programming takes control of the keyboard :) – Paul Russell Feb 20 '19 at 09:42
 
    