问题
How to handle json requests and parse the request parameters in dropWizard?
@POST
@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String test(@Context final HttpServletRequest request) {
JSONObject data=new JSONObject();
System.out.println(request);
System.out.println(request.getParameterMap());
System.out.println(">>>>>>>>>");
return "{\"status\":\"ok\"}";
}
I wrote the above code and tried the following request.
curl -XPOST -H "Content-Type: application/json" --data {"field1":"val1", "field2":"val2"} http://localhost:8080/test
But request.getParameterMap()
is {}
How to parse the parameters without writing a wrapper class?
回答1:
Your curl
command may need some additional quotes around the data (I'm getting an error without them):
curl -H "Content-type: application/json" -X POST -d '{"field1":"tal1", "field2":"val2"}' http://localhost:8080/test
You are sending a POST
request without URL
parameters. I'm not sure why you are expecting to see something there.
I don't know which version of dropwizard
you are using but I couldn't make the combination of @POST
and @Path("/something")
annotation to behave when a method is annotated. I'm getting HTTP ERROR 404
.
To make it work I have to move the @Path
annotation to the resource/class level and leave only the @Post
annotation at the method.
@Path("/test")
public class SimpleResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String test(final String data) throws IOException {
System.out.println("And now the request body:");
System.out.println(data);
System.out.println(">>>>>>>>>");
return "{\"status\":\"ok\"}";
}
}
To get the body of the request as String
just do as above. Taken from here: How to get full REST request body using Jersey?
The console looks like:
INFO [2016-11-24 15:26:29,290] org.eclipse.jetty.server.Server: Started @3539ms
And now the request body:
{"field1":"tal1", "field2":"val2"}
>>>>>>>>>
来源:https://stackoverflow.com/questions/40784962/parse-request-parameters-without-writing-wrapper-class