-1

I wish to code the Rest Controller in spring-boot for my webhook. I am creating a google action, with simple actions.

  • This is a boilerplate: https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java/blob/master/src/main/java/com/example/ActionsServlet.java.
  • I want to do the same, only in spring-boot. I want to manipulate JSON body as input, but not sure how to do this.

    @RestController
    public class indexController extends HttpServlet {
    
    
    @Autowired
    private App actionsApp;
    
    //handle all incoming requests to URI "/"
    // @GetMapping("/")
    //  public String sayHello() {
    //    return "Hi there, this is a Spring Boot application";}
    
    private static final Logger LOG = LoggerFactory.getLogger(MyActionsApp.class);
    
    //handles post requests at URI /googleservice
    @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<String> getPost(@RequestBody String payload, 
      @RequestHeader String header, HttpServletResponse response) throws IOException {
      //Not sure what to do here. 
    
    
    System.out.println(jsonData);
    
    return ResponseEntity.ok(HttpStatus.OK);
    try {
    
        //writeResponse(response, jsonResponse);
        //String med request body og object that has all request header entries
        String jsonResponse = actionsApp.handleRequest(body, listAllHeaders(header)).get();
    
    
        return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
    
    
    } catch (
            InterruptedException e) {
        System.out.println("Something wrong happened, interupted");
    } catch (
            ExecutionException e) {
        System.out.println("Something wrong happened, execution error");
    }
    

    }

Ahmed Lotfy
  • 1,065
  • 2
  • 15
  • 33

1 Answers1

0

First, there is an error in your code. There might be a wrong "return" before your function logic.

return ResponseEntity.ok(HttpStatus.OK);

Second, as you are using Spring Framework, and you use "@RequestBody String payload" in the method, the Spring Framework will take the request body and set it to payload. If you set payload as a specific type. The framework will deserialize the body to it.

Finally, you can directly use payload in your code. The value of it would be the request body.

If you want to decode the json string. You can use org.json library.

JSONObject obj = new JSONObject(payload);
String name = obj.optString("name");

The code will get the value of name in the json.

Jack Jia
  • 5,268
  • 1
  • 12
  • 14