这里采用短信发送作为案例,先发送post请求,然后解析xml。
1.导入Maven
pom.xml
<!– 解析xml –>
<!– https://mvnrepository.com/artifact/dom4j/dom4j –>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
2.编写发送请求和解析类
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
public void sendMessage(Verification verification) {
// TODO 短信发送
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("userid", "");
params.add("account", "");
params.add("password", "");
params.add("mobile", verification.getVoContent());
params.add("content", "【笨猪网】您的验证码为["+verification.getVoVerification()+"]");
params.add("action", "send");
params.add("sendTime", "");
params.add("extno", "");
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//执行HTTP请求,将返回的结构使用ResultVO类格式化
ResponseEntity<String> response = client.exchange("请求的地址", method, requestEntity, String.class);
String xml = response.getBody();
try {
Document dom = DocumentHelper.parseText(xml);
Element root=dom.getRootElement();
//写入数据库记录,可以自己写
this.messageInfoMapper.insertMessageInfo(new MessageInfo(null, verification.getVoContent(), root.element("returnstatus").getText(), root.element("message").getText(), root.element("taskID").getText(), DateUtil.getNow()));
} catch (DocumentException e) {
// TODO 处理异常
e.printStackTrace();
}
}
评论