2

I would like to read POST data from a Spring Boot controller.

I have tried all the solutions given here: HttpServletRequest get JSON POST data, but I still am unable to read post data in a Spring Boot servlet.

My code is here:

package com.testmockmvc.testrequest.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest")
    @ResponseBody
    public String testGetRequest(HttpServletRequest request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}

I have tried using the Collectors as an alternative, and that does not work either. What am I doing wrong?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
atul
  • 93
  • 1
  • 1
  • 8

1 Answers1

8

First, you need to define the RequestMethod as POST. Second, you can define a @RequestBody annotation in the String parameter

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest", method = RequestMethod.POST)
    public String testGetRequest(@RequestBody String request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}
fmodos
  • 4,472
  • 1
  • 16
  • 17
  • Adding the "method=RequestMethod.POST" did not make any difference. I cannot add the "@ResponseBody" as an annotation to the parameter. I can only add it as an annotation to the method itself. – atul Jan 19 '18 at 19:29
  • I just adjusted the answer.. adding the RequestBody instead of ResponseBody annotation, my mistake. – fmodos Jan 19 '18 at 19:30
  • Quick update: I was using the same method for handling GET and POST requests, but adding the RequestBody annotation required me to have two different methods, one for GET and another for POST. – atul Jan 19 '18 at 22:11