Reputation: 37
When I send a specific message to my Twilio number, I want to take an action depending on what that message is. The problem is, request.body()
is returning the entire request, not just the body.
I've followed the Twilio guide for creating a webhook here: https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-java and have modified it to look at what the request body is, compare that with what I'm looking for, then respond as required.
The problem is as described, when I look at req.body()
, I get more than just the 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");
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();
});
}
So, Spark starts up fine, then I set the URL accordingly in Twilio, then send a message. The message is received, but the System.out.println(req.body());
is returning this:
ToCountry=GB&ToState=&SmsMessageSid=SMc52bea78ca1df688d3d20cxxxxxxxxxx&NumMedia=0&ToCity=&FromZip=&SmsSid=SMc52bea78ca1df688d3d20cxxxxxxxxxx&FromState=&SmsStatus=received&FromCity=&Body=Hello&FromCountry=GB&To=%2B44xxxxxxxxxx&ToZip=&NumSegments=1&MessageSid=SMc52bea78ca1df688d3d20cxxxxxxxxxx&AccountSid=AC4394b4cfb2bdcefb90c592xxxxxxxxxx&From=%2B44xxxxxxxxxx&ApiVersion=2010-04-01
Whereas I would have expected (in this instance) Hello
.
I'm confused because I see Hello
in there, with the appropriate Body
tag, but it's not parsing just that.
Upvotes: 1
Views: 423
Reputation: 2798
It seems like spark parses post form data as queryParams (it is weird because the name implies GET). So
Call req.queryParams("Body") instead.
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();
});
}
Upvotes: 2