java调用企业微信发送消息的代码
时间: 2024-06-10 20:03:47 浏览: 128
可以使用企业微信提供的API实现发送消息。以下是一个示例代码:
```
import java.io.*;
import java.net.*;
import java.util.*;
public class SendMessage {
public static void main(String[] args) {
String corpid = "企业ID";
String corpsecret = "应用Secret";
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
String token = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
token = response.toString();
} catch (Exception ex) {
System.out.println("异常:" + ex);
}
String access_token = "";
try {
access_token = (new org.json.JSONObject(token)).getString("access_token");
} catch (Exception ex) {
System.out.println("异常:" + ex);
}
String msg = "Hello World!";
String touser = "UserID1|UserID2";
String toparty = "";
String totag = "";
String agentid = "应用ID";
String url_send = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token;
try {
URL obj = new URL(url_send);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
String postBody = "{\"touser\":\"" + touser + "\",\"toparty\":\"" + toparty + "\",\"totag\":\"" + totag + "\",\"msgtype\":\"text\",\"agentid\":\"" + agentid + "\",\"text\":{\"content\":\"" + msg + "\"}}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postBody);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("发送结果:" + response.toString());
} catch (Exception ex) {
System.out.println("异常:" + ex);
}
}
}
```
请注意,您需要替换代码中的企业ID,应用Secret,应用ID,用户ID和消息内容。