【问题标题】:How to code restcontroller for google actions?如何为谷歌操作编写restcontroller?
【发布时间】:2019-11-20 19:40:35
【问题描述】:

我希望在spring-boot 中为我的 webhook 编写 Rest Controller 代码。我正在使用简单的操作创建一个 google 操作。

  • 这是一个样板:https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java/blob/master/src/main/java/com/example/ActionsServlet.java
  • 我也想这样做,只是在spring-boot。我想将 JSON 正文作为输入进行操作,但不知道该怎么做。

    @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");
    }
    

    }

【问题讨论】:

  • 对我来说,你想要达到的目标并不是很清楚。

标签: java azure spring-boot docker google-home


【解决方案1】:

首先,您的代码有错误。您的函数逻辑之前可能有错误的“返回”。

return ResponseEntity.ok(HttpStatus.OK);

其次,当您使用 Spring Framework,并且在方法中使用“@RequestBody String payload”时,Spring Framework 将获取请求正文并将其设置为有效负载。如果您将有效负载设置为特定类型。该框架会将主体反序列化为它。

最后,您可以直接在代码中使用有效负载。它的值将是请求正文。

如果你想解码 json 字符串。您可以使用 org.json 库。

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

代码将获取json中name的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多