关于java 使用钉钉机器人发布群消息
懒得写基本逻辑 ,代码有注解
#具体代码:
1、测试类:
package test1;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class StarterAPP {
public static void main(String []args) throws IOException {
SendDemo sendHttp=new SendDemo();
Map<String,Object> json=new HashMap<String,Object>();
Map<String,Object> text=new HashMap<String, Object>();
json.put("msgtype","text");//设置传入参数类型 不能少
text.put("content","11 显示内容 数据 ");//机器人关键词11 测试 是其他需要显示的内容 不能少关键词
json.put("text",text);//添加参数
String url="https://oapi.dingtalk.com/robot/send?access_token=ac14635a46c55ed37badf41f082f48b8f31bff846fb5b7818ce40f1403745d60";
sendHttp.sendByMap(url,json);
System.out.println("main结束");
}
}
2、 具体请求的类:
package test1;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
public class SendDemo {
public static void sendByMap(String url, Map<String,Object> jsonMap) {
System.out.println("sendByMap 开始执行");
//URL实例的创建
URL realUrl= null;
try {
realUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//获取urlconnection 的实例
URLConnection connection= null;
try {
connection = realUrl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
//设置通用头信息
if (connection != null) {
connection.setRequestProperty("accept", "*/*");
}
if (connection != null) {
connection.setRequestProperty("connection", "Keep-Alive");
}
if (connection != null) {
connection.setRequestProperty("user-agent","Fiddler");
}
if (connection != null) {
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
}
//使用post 必须要设置的
if (connection != null) {
connection.setDoInput(true);
}
if (connection != null) {
connection.setDoOutput(true);
}
// 关于输入输出流的相关类
PrintWriter printWriter=null;
BufferedReader bufferedReader=null;
//实例化printWrite实例并 获取connection 实例的 输出流
try {
printWriter=new PrintWriter(connection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
printWriter.print(JSON.toJSONString(jsonMap));///发送请求参数
System.out.println("json.toJSonString(jsonMAp):"+JSON.toJSONString(jsonMap));
printWriter.flush();//输出缓存
//获取输入流
try {
bufferedReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
if((line=bufferedReader.readLine())!=null)
{
line+=bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("line:"+line);
}
}
3、pom.xml JSON 包 的引入
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>