1. 程式人生 > 實用技巧 >Java程式碼用指定的企業微信群機器人傳送訊息

Java程式碼用指定的企業微信群機器人傳送訊息

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方法即可傳送訊息