当我向Twilio号码发送特定消息时,我想根据该消息是什么来采取措施。问题在于,Route
返回的是整个请求,而不仅仅是正文。
我已遵循Twilio指南在此处创建Webhook: https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-java 并对其进行了修改,以查看请求主体是什么,将其与我正在寻找的内容进行比较,然后根据需要进行响应。
问题如上所述,当我看着request.body()
时,我得到的不仅仅是身体。
req.body()
因此,Spark启动正常,然后我在Twilio中相应地设置了URL,然后发送了一条消息。消息已收到,但是public static void main(String[] args) {
int portNumber = 80;
if(args.length > 0){
portNumber = Integer.parseInt(args[0]);
}
port(portNumber);
get("/", (req, res) -> "Hello Web");
post("/sms", (req, res) -> {
res.type("application/xml");
System.out.println(req.body());
String messageToSpend = req.body();
if (req.body().equals("hello")){
System.out.println("You said hello");
}
Body body = new Body
.Builder(messageToSend)
.build();
Message sms = new Message
.Builder()
.body(body)
.build();
MessagingResponse twiml = new MessagingResponse
.Builder()
.message(sms)
.build();
return twiml.toXml();
});
}
返回此消息:
ToCountry = GB&使用toState =&SmsMessageSid = SMc52bea78ca1df688d3d20cxxxxxxxxxx&NumMedia = 0&ToCity =&FromZip =&SmsSid = SMc52bea78ca1df688d3d20cxxxxxxxxxx&FromState =&SmsStatus =接收&FromCity =及身体=你好&FromCountry = GB&要=%2B44xxxxxxxxxx&ToZip =&NumSegments = 1&MessageSid = SMc52bea78ca1df688d3d20cxxxxxxxxxx&AccountSid = AC4394b4cfb2bdcefb90c592xxxxxxxxxx&从=%2B44xxxxxxxxxx&ApiVersion = 2010-04-01 >
在这种情况下,我本来期望System.out.println(req.body());
。
我很困惑,因为我在其中看到Hello
并带有适当的Hello
标签,但它并不能完全解析。
答案 0 :(得分:1)
似乎spark将post表单数据解析为queryParams(这很奇怪,因为名称暗示GET)。所以
请致电req.queryParams(“ Body”)。
public static void main(String[] args) {
int portNumber = 80;
if(args.length > 0){
portNumber = Integer.parseInt(args[0]);
}
port(portNumber);
get("/", (req, res) -> "Hello Web");
post("/sms", (req, res) -> {
res.type("application/xml");
// Remove this: System.out.println(req.body());
String messageToSpend = req.queryParams("Body");
if ("hello".equals(messageToSpend)){
System.out.println("You said hello");
}
Body body = new Body
.Builder(messageToSend)
.build();
Message sms = new Message
.Builder()
.body(body)
.build();
MessagingResponse twiml = new MessagingResponse
.Builder()
.message(sms)
.build();
return twiml.toXml();
});
}