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

前端 未结 4 718
南方客
南方客 2020-12-16 10:35

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.

相关标签:
4条回答
  • 2020-12-16 10:53

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

    0 讨论(0)
  • 2020-12-16 10:58

    At some point of time Jersey ContainerServlet (or other Jersey object during request processing) calls request.getInputStream() or request.getReader() which set 'usingInputStream' or 'usingReader' to TRUE. This state prevents populating of parameters map inside the request object. Something like this:

    parseParameters() {
        if (usingInputStream || usingReader) {
            return; 
        } else {
            parametersMap.putAll({actual parameters parsing from stream})
        }
    } 
    
    Map getParametersMap() {
        return parametersMap;
    }
    

    Try putting a break point at the very first entry point (beginning of Jersey ServletContainer.service() method) of your application and evaluate request.getParametersMap() call. You'll get your parameters.

    0 讨论(0)
  • 2020-12-16 11:07

    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) {
    //...
    }
    
    0 讨论(0)
  • 2020-12-16 11:12

    If you are using Jersey RESTful API in JAVA you can look for Parameter Annotations (@*Param)

    Example:

    Dependency:

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.8</version>
    </dependency>
    

    Code:

    package yourpack;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.core.Response;
    
    @Path("/path_to_data")
    public class DataResource {
        @GET
        @Path("/{param}")
        public Response getMsg(@PathParam("param") String urlparam) {
            int ok = 200;
            String result = "Jersey Data resource: " + urlparam;
    
            return Response.status(ok).entity(result ).build();
        }
    }
    

    List of annotations: @MatrixParam, @HeaderParam, @CookieParam, @FormParam, @QueryParam, @PathParam

    0 讨论(0)
提交回复
热议问题