Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read POST parameters for a RESTful service using Jersey?

Tags:

java

rest

jersey

I am not using JSON or anything like that. I have a simple form to upload a file and I want to read the parameters of the form. The code below is not working as expected. It will not show any parameters.

@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("{appNum}/{docId}/file") public Response uploadDocFile(         @PathParam("appNum") String appNum,         @PathParam("docId") String docId,         @Context HttpServletRequest req) {      try {          log.info("POST Parameters:");          Enumeration e = req.getParameterNames();          while(e.hasMoreElements())         {             Object key = e.nextElement();             log.info("Key: " + key);             log.info("Val: " + req.getParameter(key.toString()));         }       }  catch (Exception e) {         e.printStackTrace();         return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new StatusResponse(e)).build();     }      return Response.ok().build(); } 
like image 892
Rocky Pulley Avatar asked May 23 '11 12:05

Rocky Pulley


People also ask

How do you access parameters in a rested POST method?

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers: @POST @Path("/create") public void create(@HeaderParam("param1") String param1, @HeaderParam("param2") String param2) { ... }

What are the features of Jersey RESTful web services?

Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation. Jersey framework is more than the JAX-RS Reference Implementation.


2 Answers

FYI, You need to use @FormParam. Also make sure INPUT HTML types are using name= not id=.

like image 58
Rocky Pulley Avatar answered Oct 20 '22 05:10

Rocky Pulley


I have the same problem. Using @FormParam annotation for individual parameters works, but reading them from HttpServletRequest injected through @Context doesn't. I also tried to get the request object/parameters through Guice using Provider<HttpServletRequest> and @RequestParameters<Map<String, String[]>>. In both cases there were no post parameters.

However, it is possible to get a map of parameters by adding a MultivaluedMap<String, String> parameter to resource method. Example:

@POST public void doSomething(MultivaluedMap<String, String> formParams) { //... } 
like image 26
Jamol Avatar answered Oct 20 '22 04:10

Jamol