码迷,mamicode.com
首页 > 微信 > 详细

Java代码用指定的企业微信群机器人发送消息

时间:2020-12-31 12:09:45      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:utils   methods   har   请求   header   div   apache   ati   artifact   

1.我们通过Java来向某个WebHook地址发送POST请求,并携带我们需要发送的消息
2.代码示例
搭建Maven项目,在pom.xml文件里引入httpclient依赖

1 <dependency>
2     <groupId>org.apache.httpcomponents</groupId>
3     <artifactId>httpclient</artifactId>
4     <version>4.5.3</version>
5 </dependency>

以下是java代码的实现部分

 1 package com.demo;
 2 import org.apache.http.HttpResponse;
 3 import org.apache.http.HttpStatus;
 4 import org.apache.http.client.HttpClient;
 5 import org.apache.http.client.methods.HttpPost;
 6 import org.apache.http.entity.StringEntity;
 7 import org.apache.http.impl.client.HttpClients;
 8 import org.apache.http.util.EntityUtils;
 9 
10 public class ChatbotSend {
11     //企业微信群机器人的WebHook地址xxx
12     public static String WEBHOOK_TOKEN = "xxx";
13     
14     public static void main(String args[]) throws Exception {
15         HttpClient httpclient = HttpClients.createDefault();
16         HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
17         httppost.addHeader("Content-Type", "application/json; charset=utf-8");
18         //构建一个json格式字符串textMsg,其内容是接收方需要的参数和消息内容 
19         String textMsg = "{\"msgtype\":\"text\",\"text\":{\"content\":\"你好,我是机器人\"},\"at\":{\"atMobiles\":[\"xxx\"],\"isAtAll\":false}}";
20         StringEntity se = new StringEntity(textMsg, "utf-8");
21         httppost.setEntity(se);
22         HttpResponse response = httpclient.execute(httppost);
23         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
24             String result = EntityUtils.toString(response.getEntity(), "utf-8");
25             System.out.println(result);
26         }
27     }
28 }

执行main方法即可发送消息

Java代码用指定的企业微信群机器人发送消息

标签:utils   methods   har   请求   header   div   apache   ati   artifact   

原文地址:https://www.cnblogs.com/doubleflower/p/14193446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!