我正在尝试解析发送到 API V2 中基于 Java 的实现的请求。我在 API 的 V2 中找不到任何用于在 Java 中执行此操作的示例文档(我的项目中的 com.google.cloud:google-cloud-dialogflow:0.38.0-alpha 依赖项)。
到目前为止,我已经编写了一个非常基本的 Spring MVC Controller 来接受请求。
如何解析请求中的负载,例如对话流发送的参数?
import com.google.cloud.dialogflow.v2beta1.WebhookRequest;
import com.google.cloud.dialogflow.v2beta1.WebhookResponse;
import com.google.protobuf.Descriptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("test")
public class TestRequestRestController {
private static final Logger log = LoggerFactory.getLogger(TestRequestRestController.class);
@PostMapping("test1t")
public WebhookResponse getTest1(WebhookRequest request) {
System.out.println(request.toString());
return WebhookResponse.newBuilder().setFulfillmentText("Example reply 1 ").build();
}
}
最佳答案
不确定 WebhookRequest
和 WebhookResponse
。
以下代码可能对您有所帮助。
import org.springframework.http.HttpEntity;
@PostMapping("test1t")
public String getTest1(HttpEntity<String> httpEntity) {
String reqObject = httpEntity.getBody();
System.out.println("request json object = "+reqObject);
//Get the action
JSONObject obj = new JSONObject(reqObject);
String action = obj.getJSONObject("result").getString("action");
//Get the parameters
JSONObject params = obj.getJSONObject("result").getJSONObject("parameters");
String response = "Hello from Java.";
return "{'speech': '"+response+"', 'displayText':'"+response+"'}";
}
关于java - 在 V2 DialogFlow fulfillment webhook 中访问请求负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654196/