注册企业微信
填写企业微信部分信息
1.打开一下网站,填写部分信息。
https://work.weixin.qq.com/wework_admin/register_wx?from=myhome_baidu

2.登陆进去后,找到"我的企业" 下拉找到 "企业ID/corpid" 这个记录一下后面会用到

在企业微信内生成应用
1.找到"应用管理" ==>> "自建" ==>> "创建应用"

2.随便选择一张图片,修改图片的大小为 750*750 创建应用需要图标

3.选择上一步创建的图片,填写应用信息

4.记录 "Agentid" "Secret" 后面会用


5.配置企业可用IP
里面需要企业的域名,在域名下放一个文件

上面这个配置不通过一直会报错:
{"errcode":60020,"errmsg":"not allow to access from your ip, hint: [***], from ip: ***, more info at https://open.work.weixin.qq.com/devtool/query?e=60020"}
调用代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class SendMessage {
public static String get_access_token(String corpid,String secret) throws Exception {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+secret;
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = "";
String line;
while ((line = br.readLine()) != null) {
response += line;
}
br.close();
if(responseCode == 200){
JSONObject jsonObject = new JSONObject(response);
String errcode = jsonObject.getString("errcode");
if(errcode.equals("0")){
String access_token = jsonObject.getString("access_token");
System.out.println(access_token);
return access_token;
}
System.out.println(response);
}
return "";
}
public static void send_message(String touser,String content) throws Exception {
String agentid = "agentid";
String access_token = get_access_token("corpid","Secret");
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?debug=1&access_token="+access_token;
String requestBody = "{\"touser\":\""+touser+"\",\"msgtype\":\"text\",\"agentid\":"+agentid+"," + "\"text\":{\"content\":\""+content+"\"}}";
System.out.println(requestBody);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = "";
String line;
while ((line = br.readLine()) != null) {
response += line;
}
br.close();
if(responseCode == 200){
JSONObject jsonObject = new JSONObject(response);
String errcode = jsonObject.getString("errcode");
if(errcode.equals("0")){
System.out.println("发送成功");
return ;
}
}
System.out.println(response);
System.out.println("发送失败");
}
public static void main(String[] args) throws Exception {
//将整体代码放到一个服务里面,参数为收件人|内容 这样就封装成一个企业微信 发送的服务了
send_message("发送的用户","发送的内容:告警测试最终版1");
}
}