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

6
  • i'm using angular JS for integration Commented Jan 30, 2017 at 12:58
  • share the request made in the browser . capture the request in network tabs Commented Jan 30, 2017 at 13:01
  • We need to know how you're calling this request... Please share the details Commented Jan 30, 2017 at 13:03
  • [link]s30.postimg.org/hu2kklng1/sc1.png and [link] s30.postimg.org/afd8s81kh/sc_2.png.. its working in localhost. i'm getting error in live server Commented Jan 30, 2017 at 13:09
  • any server side exception? Commented Jan 30, 2017 at 13:25

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

6 Comments

Actually i want to pass some other parameters with json like s30.postimg.org/afd8s81kh/sc_2.png
I updated the answer to show how to add other parameters
Can you tell me how retrive data from POST method?? i'm trying with HttpServletRequest params but its giving null values
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.
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.