背景介绍:
再看已有的项目中关于Http请求的接口方法,使用的都是 RestTemplate , 正好遇到我正在学习使用HuTool工具包,也是为了找点儿乐子,故当即决定使用新学的工具进行改造实现。这里是以发送企业微信提醒的方法为例。
改造前源代码如下:
public ResponseEntity<String> sendWeChatMsg(String callPhone) {
RestTemplate restTemplate = new RestTemplate();
String content = "IP地址172.168.20.158无法PING通或已断电,请及时处理。";
Integer agentId = 1000004;
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("content", content);
map.add("agentId", agentId);
map.add("receiver", callPhone);
HttpHeaders headers = new HttpHeaders();
String Token = "A9D9999F666D6D88";
headers.add(HttpHeaders.AUTHORIZATION, Token);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> httpEntity = new HttpEntity(map, headers);
String SendMsgUrl = "http://www.itheibai.com:8092/oa/msg/send/wechat";
return restTemplate.postForEntity(SendMsgUrl, httpEntity, String.class);
}
改造后源代码如下:
public HttpResponse sendWeChatMsg(String callPhone) {
HashMap<String, Object> paramMap = new HashMap<>();
String content = "IP地址172.168.20.158无法PING通或已断电,请及时处理。";
paramMap.put("content", content);
Integer agentId = 1000004;
paramMap.put("agentId", agentId);
paramMap.put("receiver", callPhone);
Map<String, String> headers = new HashMap<>();
String Token = "A9D9999F666D6D88";
headers.put(HttpHeaders.AUTHORIZATION, Token);
headers.put(Header.CONTENT_TYPE.toString(), MediaType.APPLICATION_FORM_URLENCODED.toString());
String SendMsgUrl = "http://www.itheibai.com:8092/oa/msg/send/wechat";
return HttpRequest.post(SendMsgUrl).addHeaders(headers).form(paramMap).execute();
}
两种方式的区别:
返回的类型格式不同,对body的取值方式不同。可以自己测一下,选择自己喜欢的方式。
评论前必须登录!
注册