Search code examples
javaandroidservletsjakarta-eeokhttp

Get OkHttp PUT request parameters in Servlets


I'm making a PUT request using OkHttp 4.9.1 from my Android app as below,

RequestBody reqBody = new FormBody.Builder()
        .add("name", name)
        .add("phone", phone)
        .build();

Request request = new Request.Builder()
        .url(API_URL)
        .put(reqBody)
        .build();

new OkHttpClient().newCall(request).enqueue(new Callback() {
    ...
});

The request comes to the server but the problem is I cannot access the parameters from the Servlet,

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("NAME: " + req.getParameter("name"));
    System.out.println("PARAMS: " + new HashMap(req.getParameterMap()).toString());
    System.out.println("CT: " + req.getContentType());
}

below is the output log from the server,

NAME: null
PARAMS: {}
CT: application/x-www-form-urlencoded

As you can see the parameter map is empty. What am I missing?


Solution

  • request.getParameter() is not working in Servlets when it comes to PUT requests. So this was not a problem with OkHttp. As to why request.getParameter() is not working in doPut(...) refer the post below,

    Servlet request.getParameter() returns null in PUT but not in POST