I'm very new to using Spring, and all the things involved, but I'm trying to get through this.
I'm trying to make a service, using the Spring MVN and Gradle, to understand a JSON-formatted String. It's all made in Java. But I can't get it to work as it should, at all.
This
@RequestMapping(value = "/toggle")
public @ResponseBody String sendCommand(@RequestParam(value="IP") String IP){
//body
}
Is a method in my Controller, but, when I send the following JSON-formatted String
{"IP":"192.168.1.9"}
I still get the Response Code 400.
I've tried different variations, one example using a @RequestBody instead, with an own class for the indata. And another where I recieve a HttpEntity, to watch whether the String was recieved correctly. While the String is recieved correctly, I can't get my code to "read" it.
I can go to localhost:8080/toggle, and through HTTP set the variables, say:
http://localhost:8080/toggle?IP=192.168.1.9
works.
Where would you suggest to continue troubleshooting? Thanks in advance!
EDIT: Wow. Thanks a lot for quick replies, I was expecting a day or two to go without replies, instead I got your help within minutes. I knew this site was good, but you are great, thanks!
That said, I made a new class called Ident, which has only a private String variable, with constructor, setter and getter. Now I have
@RequestMapping(value = "/toggle")
public @ResponseBody String sendCommand(@RequestBody Ident ident) {
//body
}
I still get 400 sending the same String though.
And while it would work using a @PathVariable, I'd like getting this to work, because now I'm only experimenting with it. It will be used to send more than only the IP later on.
I'm using @ComponentScan @EnableAutoConfiguration in the main-file, might that have something to do with things - that it gets set up wrong?
Your Method Should be like,
here IP is placeholder that can accommodate any passed IP.
and your URL request should be like
http://localhost:8080/toggle/192.168.1.9 // [as per RESTful URL principle ]
You are mixing to different thing (request parameters and json objects).
In order to catch the POSTed
{"IP":"192.168.1.9"}
you need to do something like the following:You also need to create a class that corresponds to the json and map that json to the class (using a library like jackson).
If you want to forgo the creation of the intermediate object (which I do not propose you do since it makes the code cleaner), you could just extract the IP from the json String using standard JDK methods