0

I'm trying to send json string to Spring controller, i'm getting 400 - bad request as response

i'm using Spring 4.0.3

This is my controller

@Controller
public class Customer{

    @RequestMapping(value = "/apis/test", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody String test(HttpServletRequest params) throws JsonIOException {
        String json = params.getParameter("json");
        JsonParser jObj = new JsonParser();
        JsonArray  jsonObj = (JsonArray ) jObj.parse(json);

        for(int i = 0; i < jsonObj.size(); i++) {
            JsonObject jsonObject = jsonObj.get(i).getAsJsonObject();
            System.out.println(jsonObject.get("name").getAsString());

        }
        return json;
    }
}

Please help me to solve this

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

1
@RequestMapping(value = "/apis/test", method = RequestMethod.GET, produces = "application/json")

The above means this is a HTTP GET method which does not normally accept data. You should be using a HTTP POST method eg:

@RequestMapping(value = "/apis/test", method = RequestMethod.POST, consumes = "application/json")
    public @ResponseBody String test(@RequestParam final String param1, @RequestParam final String param2, @RequestBody final String body) throws JsonIOException {

then you can execute POST /apis/test?param1=one&param2=two and adding strings in the RequestBody of the request

I hope this helps!

ozOli
  • 1,414
  • 1
  • 18
  • 26
  • Actually i want to pass some other parameters with json like https://s30.postimg.org/afd8s81kh/sc_2.png – Sabarimani Radhakrishnan Jan 30 '17 at 13:55
  • I updated the answer to show how to add other parameters – ozOli Jan 30 '17 at 14:09
  • Can you tell me how retrive data from POST method?? i'm trying with HttpServletRequest params but its giving null values – Sabarimani Radhakrishnan Jan 30 '17 at 14:18
  • the code above shows you how to get the parameters, use RequestParam and RequestBody annotated method parameters. you can use HttpServletRequest but that is a bit more lower level. – ozOli Jan 30 '17 at 14:30
  • Can you please tell me how to get more that 10 params by usingGET and POST method in better way?? actually i'm not getting correct way.. i have tried many examples.but in post method its creating issues – Sabarimani Radhakrishnan Jan 30 '17 at 15:21
  • hi the code in this question should help you http://stackoverflow.com/questions/27732133/httpservletrequest-getparametermap-vs-getparameternames – ozOli Jan 30 '17 at 15:41