<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.3.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.45</version> </dependency> </dependencies>
建立RestTemplate配置類,將RestTemplate注入容器中
/** * RestTemplate配置類 * @Author Sans * @CreateTime 2019/4/2 09:55 */ @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
Controller測試
/** * 測試短信DEMO * @Author Sans * @CreateTime 2019/4/2 09:39 */ @RestController @RequestMapping("/sms") public class TestController { @Autowired private RestTemplate restTemplate; /** * 單發短信測試 * @Author: Sans * @CreateTime: 2019/4/2 10:06 */ @RequestMapping(value = "/sendsmsTest",method = RequestMethod.GET) public String sendsmsTest(){ //單發短信API String url = "https://open.ucpaas.com/ol/sms/sendsms"; JSONObject jsonObject = new JSONObject(); //基礎配置,在開發平台認證后獲取 jsonObject.put("sid","ad024f8****************05d1614"); jsonObject.put("token","5ddbf62d4d****************e27402c"); jsonObject.put("appid","0ceaca4708****************76ec45f"); //模板ID,在開發平台創建模板對應的模板ID jsonObject.put("templateid", "432116"); //模板對應的參數,參數之間拼接用逗號作為間隔符 jsonObject.put("param", "1315,500"); //要發送的手機號 jsonObject.put("mobile", "用戶的手機號"); //用戶透傳ID,隨狀態報告返回,可以不填寫 jsonObject.put("uid",""); String json = JSONObject.toJSONString(jsonObject); //使用restTemplate進行訪問遠程服務 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers); String result = restTemplate.postForObject(url, httpEntity, String.class); return result; } /** * 群發短信測試 * @Author: Sans * @CreateTime: 2019/4/2 11:23 */ @RequestMapping(value = "/sendBatchsmsTest",method = RequestMethod.GET) public String sendBatchsmsTest(){ //群發短信API String url = "https://open.ucpaas.com/ol/sms/sendsms_batch"; JSONObject jsonObject = new JSONObject(); //基礎配置,在開發平台認證后獲取 jsonObject.put("sid","ad024f8****************05d1614"); jsonObject.put("token","5ddbf62d4d****************e27402c"); jsonObject.put("appid","0ceaca4708****************76ec45f"); //模板ID,在開發平台創建模板對應的模板ID jsonObject.put("templateid", "432116"); //模板對應的參數,參數之間拼接用逗號作為間隔符 jsonObject.put("param", "1315,500"); //群發多個手機號之間要用逗號作為間隔符 jsonObject.put("mobile", "用戶的手機號A,用戶的手機號B"); //用戶透傳ID,隨狀態報告返回,可以不填寫 jsonObject.put("uid",""); String json = JSONObject.toJSONString(jsonObject); //使用restTemplate進行訪問遠程服務 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers); String result = restTemplate.postForObject(url, httpEntity, String.class); return result; } }
https://www.jb51.net/article/160092.htm