注意:当你在我显示代码的地方看到
postmapping-url-here
和MyOwnDefinedEntity
时,它只是意味着我试图不透露太多。
所以我正在使用Twilio
发送和接收短信。我现在已经坚持这个问题大约3天了,我似乎无法弄清楚如何解决它。
我使用Spring Boot
作为应用程序框架,Gradle
作为构建工具,VSCode
作为IDE。我也在使用Ngrok
to为localhost:8080
创建一个隧道来运行。
当我把它作为一个:
public static void main(String[] args) {
}
它工作得很好,我的Twilio
号码发回了一个文本作为回应。
但是,当我把它放在它自己的函数中,调用该函数,并使用整个应用程序运行它时,我仍然得到200
的相同状态代码,当它作为main
方法工作时,但我的Twilio
数字不会发送文本我回来了。
我尝试过使用@PostMapping
和@GetMapping
,因为我已经尝试过测试POST
和GET
。
在我从Twilio
网站发送和接收代码时,我尝试使用application/xml
和application/json
作为响应类型。
这是我到目前为止的一些代码:
public static void TwilioRespondToSMS() {
get("/", (req, res) -> "");
post("/<postmapping-url-here>", (req, res) -> {
res.type("application/xml");
Body body = new Body
.Builder("This is a response to your text message")
.build();
Message sms = new Message
.Builder()
.body(body)
.build();
MessagingResponse twiml = new MessagingResponse
.Builder()
.message(sms)
.build();
return twiml.toXml();
});
}
这是main
代码:
@SpringBootApplication
public class ApplicationServerClass {
public static void main(String[] args) {
SpringApplication.run(ApplicationServerClass.class, args);
//TwilioRespondToSMS();
}
// Whatever other code ...
}
我也试过把我的功能放在:
@Bean
public CommandLineRunner commandRunner() {
return (args) -> {
TwilioRespondToSMS();
// Whatever other code ...
}
}
这是@PostMapping
函数:
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("/<postmapping-url-here>")
public ResponseEntity<MyOwnDefinedEntity> getMyOwnDefinedEntity(@PathVariable Long id) {
log.debug("REST request to get MyOwnDefinedEntity : {}", id);
Optional<MyOwnDefinedEntity> myOwnDefinedEntity = myOwnDefinedEntityRepository.findById(id);
//if(myOwnDefinedEntity.isPresent())
return new ResponseEntity<MyOwnDefinedEntity>(MyOwnDefinedEntity.get(), HttpStatus.OK);
}
来自Twilio网站的例子显示它是main
功能。在使用整个应用程序运行它时,是否需要从该示例中进行更改?
提前致谢。
好吧,经过4天试图解决我的问题,我终于能够自己想出一个解决方案了。
我想也许这只是一个愚蠢的错误,我直到现在才注意到,但我觉得这个解决方案不是很容易想出来的。所以我将分享我是如何想出这个的。
在将post
函数中的URL映射到自定义@PostMapping
方法之前,我实际上获得了404
的状态代码,因为它无法识别要映射到的任何POST
请求URL。
我认为正确的解决方案是使用定制的@PostMapping
,但这只是导致我的Java Spark
使用相同的端口:8080
作为我的Spring Boot
应用程序运行的端口。这就是为什么我没有从我的Twilio号码收到任何文本,即使我得到了200
的状态代码。
所以这就是我所做的,而不是解决问题:
首先,我删除了我的自定义
@PostMapping
函数
@PostMapping("/<postmapping-url-here>")
public ResponseEntity<MyOwnDefinedEntity> getMyOwnDefinedEntity(@PathVariable Long id) {
log.debug("REST request to get MyOwnDefinedEntity : {}", id);
Optional<MyOwnDefinedEntity> myOwnDefinedEntity = myOwnDefinedEntityRepository.findById(id);
//if(myOwnDefinedEntity.isPresent())
return new ResponseEntity<MyOwnDefinedEntity>(MyOwnDefinedEntity.get(), HttpStatus.OK);
}
我保留了我的功能:
@Bean
public CommandLineRunner commandRunner() {
return (args) -> {
TwilioRespondToSMS();
// Whatever other code ...
}
}
最后,在我的TwilioRespondToSMS()
里面,我加入了:port(8070);
,或者其他任何不是8080
的端口号。
在这种情况下,Java Spark
现在通过8070
隧道网址使用Ngrok
,Spring Boot
正在使用8080
。在这一点上,我终于成功地能够在同时运行Twilio
时从我的Spring Boot
号码中获得响应文本消息。