0

I have developer a Java Servlet that works well with application/javascript requests such as:

curl -H "application/javascript" -X POST -d "action=register_user" http://example.com/api/users

I want it to accept application/json as well, because in the request below the servlet cannot detect any parameters

curl -H "Content-Type: application/json" -X POST -d '{"action":"register_user"}' http://example.com/api/users

How can I modify the servlet below to make it work with application/json?

public class Manage extends HttpServlet {

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Manage() {
    }

    public Manage(Server server) {
        super();
    }   

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings("unchecked")
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        dosomething(action);
    }
  • What does the javadoc of `getParameter` say? – Sotirios Delimanolis Mar 08 '17 at 15:39
  • 2
    Possible duplicate of [Retrieving JSON Object Literal from HttpServletRequest](http://stackoverflow.com/questions/1548782/retrieving-json-object-literal-from-httpservletrequest) – Jeremy Mar 08 '17 at 15:40
  • Previously, you POSTed a http post variable with the name "action". You don't do that anymore, which is why ``request.getParameter("action")`` will return ``null``. – f1sh Mar 08 '17 at 15:43
  • @f1sh what do you mean? In the second request I am sending a JSON with attribute "action". How can I modify the servlet in order to capture it? –  Mar 08 '17 at 16:28

0 Answers0