0

I'm developing a Backend application using Java and Servlet. I'm using Postman to simulate my client that will send me POST requests.

The thing is, my Client will send me data (key and value) using the HTTP Body part rather than params. On postman I can simulate it filling KEY and VALUE on the Body part as form-data. On the server side, people recommend this:

String login = request.getParameter("login");

But since the client is sending the parameters to me using the body, the above function returns me null (only works if I use params tab on Postman, which is not my client behavior). I was able to read the body using:

String line = null;
while ((line = request.getReader().readLine()) != null)
    System.out.println(line);

But the data I get is like:

----------------------------655577064367924555315251
Content-Disposition: form-data; name="login"

matheus

Which means that I'd have to parse that string to transform it on a map<String,String>, which I'm pretty sure that it's not the best whey to handle it.

There is any way that I can pass a KEY("login") to retrieve the VALUE(matheus) from the Body as made on params?

*** SOLUTION ***

It was missing the annotation:

@MultipartConfig
  • Thanks, the solution was just placing the annotation @MultipartConfig after @WebServlet("/WebService"). After that, String login = request.getParameter("login"); is returning the value on the body. – Gustavo Nóbrega Aug 07 '21 at 08:08

1 Answers1

0

you can do it like this;

@PostMapping("/")
public @ResponseBody
String greetingPost(HttpServletRequest httpRequest) throws Exception {
    final StringBuffer ret = new StringBuffer();
    httpRequest.getParts().stream().forEach(part -> {
        try {
            ret.append(part.getName())
                    .append(":")
                    .append(IOUtils.toString(part.getInputStream(), "UTF8"))
                    .append("\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    return ret.toString();
}
Kemal Kaplan
  • 932
  • 8
  • 21
  • You are right, we are so used to springs MVC, but, HttpServletRequest is in javax.servlet.http package, therefore it sould also work if the underlying implementation supports getParts (i.e. catalina connector) – Kemal Kaplan Aug 06 '21 at 12:04