使用 springboot 之前, 我们发送 http 消息是这么实现的
我们用了一个过时的类, 虽然感觉有些不爽, 但是出于一些原因, 一直也没有做处理, 最近公司项目框架改为了 springboot,springboot 中有一种很方便的发送 http 请求的实现, 就是 RestTemplate, 而且实现起来非常简单, 代码也很清晰.
从上面代码可以看到, 向钉钉发送的参数为一个 JSON 字符串, 所以需要的 HttpEntity 的泛型应该是 String, 如果是键值对, 就需要声明 MultiValueMap<String, String> map = new LinkedMultiValueMap<>();, 将其作为第一个参数传递到 HttpEntity 构造方法中.
MediaType 中定义了很多类型, 我们这里使用的为 APPLICATION_JSON_UTF8, 进入源码, 可以看到, 该字段对应的值为属性 APPLICATION_JSON_UTF8_VALUE 的值, 而属性 APPLICATION_JSON_UTF8_VALUE 的值为 application/JSON;charset=UTF-8, 这也正是我们需要的.
本例发送的 JSON 字符串, 查找钉钉机器人的地址比较简单, 具体步骤为 "群设置 -- 群机器人 -- 设置 -- 复制" 即可, 具体代码实现也很简单, 如下
- package com.demo.webboot;
- import javax.annotation.Resource;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.http.HttpEntity;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.MediaType;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Component;
- import org.springframework.Web.client.RestTemplate;
- @Component
- public class RestCommandLine implements CommandLineRunner {
- @Resource
- private RestTemplate restTemplate;
- @Override
- public void run(String... args) throws Exception {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
- String content = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"This is a test case.\"}, \"at\": {\"atMobiles\": [phone num], \"isAtAll\": false}}";
- HttpEntity<String> request = new HttpEntity<>(content, headers);
- String url = "https://oapi.dingtalk.com/robot/send?access_token=65eff73abfd26a3e5e11dc87c2c8bcbf359f15b65cd1d3bcb60443307fba675a1";
- ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, request, String.class);
- String body = postForEntity.getBody();
- System.out.println(body);
- }
- }
在启动类中配置 RestTemplate, 没有对 RestTemplate 做较多的处理, 直接调用 build 方法创建.
- package com.demo.webboot;
- import javax.annotation.Resource;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.Web.client.RestTemplateBuilder;
- import org.springframework.context.annotation.Bean;
- import org.springframework.Web.client.RestTemplate;
- @SpringBootApplication
- public class WebbootApplication {
- @Resource
- private RestTemplateBuilder builder;
- public static void main(String[] args) {
- SpringApplication.run(WebbootApplication.class, args);
- }
- @Bean
- public RestTemplate restTemplate() {
- return builder.build();
- }
- }
运行结果如下
通过以上简单代码, 就可以想钉钉机器人发送消息了, 当然, 这里只是一个 demo.
来源: http://www.bubuko.com/infodetail-3172617.html