Reputation: 9737
So I am standing up a rest service. It is going to request a post to a resource that is pretty complex. The actual backend requires multiple (19!) parameters. One of which is a byte array. It sounds like this is going to need to be serialized by the client and sent to my service.
I am trying to understand how I can right a method that will handle this. I am thinking something like this
@POST
@Path("apath")
@Consumes(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
public Response randomAPI(@Parameter apiID, WhatParamWouldIPutHere confused){
}
What parameter types would I do to capture that inbound (Serialized) Post data. And what would the client URI look like?
Upvotes: 0
Views: 772
Reputation: 6531
What I am thinking is you can simply use the httpservlet request and all the parameters can be retrieved as below
@RequestMapping(value = "/yourMapping", method = RequestMethod.POST)
public @ResponseBody String yourMethod(HttpServletRequest request) {
Map<String, String[]> params = request.getParameterMap();
//Loop through the parameter maps and get all the paramters one by one including byte array
for(String key : params){
if(key == "file"){ //This param is byte array/ file data, specially handle it
byte[] content = params.get(key);
//Do what ever you want with the byte array
else if(key == "any of your special params") {
//handle
}
else {
}
}
}
Upvotes: 1
Reputation: 1675
In order to get all the parameters of the request you can use @Context UriInfo
as parameter of your randomAPI
method.
Then use UriInfo#getQueryParameters()
to get the full MultivaluedMap
of parameters.
if you wish to convert the MultivaluedMap
to a simple HashMap
I added the code for that too.
so your method will basically look like something like this:
@POST
@Path("apath")
@Consumes(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
public Response randomAPI(@Context UriInfo uriInfo){
Map params= (HashMap) convertMultiToHashMap(uriInfo.getQueryParameters());
return service.doWork(params);
}
public Map<String, String> convertMultiToHashMap(MultivaluedMap<String, String> m) {
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : m.entrySet()) {
StringBuilder sb = new StringBuilder();
for (String s : entry.getValue()) {
sb.append(s);
}
map.put(entry.getKey(), sb.toString());
}
return map;
}
Additional Info :
The
@Context
annotation allows you to inject instances ofjavax.ws.rs.core.HttpHeaders
,javax.ws.rs.core.UriInfo
,javax.ws.rs.core.Request
,javax.servlet.HttpServletRequest
,javax.servlet.HttpServletResponse
,javax.servlet.ServletConfig
,javax.servlet.ServletContext
, andjavax.ws.rs.core.SecurityContext
objects.
Upvotes: 1