目的:給關注用戶推送消息
場景:自動化測試,運維監控,接口訪問等報錯預警。例如線上接口報錯,發送提醒消息
准備工作:
1:注冊企業號(為什么不用公眾號呢?)
2:常用參數介紹:
1:CORPID 企業號唯一標志符號。 位置:點擊首頁企業名稱,企業資料中有key:CorpID 2:CORPSECRET: 需要創建單獨等應用。具體步驟,按照提示一步一步來即可。需關注2個參數 Secret 和 AgentId(用於區分給哪個應用推送消息)
3:發送消息准備工作:
關注自己的企業號。(需要先綁定手機號)
4:紀錄下需要發送消息的通訊錄Id
用於給指定用戶推送消息
5:代碼結構
1:獲取token
2:發送消息
6源碼:(在你執行下面代碼的時候,AgentId改為你自己的)
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;
/**
* @author cxf
*/
public class SendWeChatMessage {
// 系統properties文件名稱
// private static final String EMAILCONFIG = "emailAndMsgConfig";
// 發送消息類型
private final static String MSGTYPE = "text";
// 發送消息分組所有成員
private final static String TOPARTY = "@all";
// 獲取配置文件中的值
private final static String CORPID = "上面提到的CORPID";// 需要自己申請,官網有試用企業號
// 可以申請試用
private final static String CORPSECRET = "上面提到的CORPSECRET";
// 獲取訪問權限碼URL
private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
// 創建會話請求URL
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
// 獲取接口訪問權限碼
public String getAccessToken() {
HttpClient client = new HttpClient();
// PostMethod post = new PostMethod(ACCESS_TOKEN_URL);
GetMethod get = new GetMethod(ACCESS_TOKEN_URL);
get.releaseConnection();
get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
NameValuePair[] param = { new NameValuePair("corpid", CORPID), new NameValuePair("corpsecret", CORPSECRET) };
// 設置策略,防止報cookie錯誤
DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
// 給post設置參數
get.setQueryString(param);
String result = null;
try {
client.executeMethod(get);
result = new String(get.getResponseBodyAsString().getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
// 將數據轉換成json
if(result==null||result==""){
System.out.println("*****************");
System.out.println("result:null");
}else {
System.out.println("result is not null:"+result.toString());
JSONObject jasonObject = JSONObject.fromObject(result);
result = (String) jasonObject.get("access_token");
// System.out.println(result);
get.releaseConnection();
}
return result;
}
/**
* 企業接口向下屬關注用戶發送微信消息(實現方式一)
*
* @param touser
* 成員ID列表(消息接收者,多個接收者用‘|’分隔,最多支持1000個)。特殊情況:指定為@all,
* 則向關注該企業應用的全部成員發送
* @param toparty
* 部門ID列表,多個接收者用‘|’分隔,最多支持100個。當touser為@all時忽略本參數
* @param totag
* 標簽ID列表,多個接收者用‘|’分隔。當touser為@all時忽略本參數
* @param content
* 消息內容
* @return
*/
@SuppressWarnings("deprecation")
public String sendWeChatMessage(String touser, String toparty, String totag, String content) {
HttpClient client = new HttpClient();
String ACCESS_TOKEN = getAccessToken();
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"touser\":" + "\"" + touser + "\",");
sb.append("\"toparty\":" + "\"" + toparty + "\",");
sb.append("\"totag\":" + "\"" + totag + "\",");
sb.append("\"msgtype\":" + "\"" + "text" + "\",");
sb.append("\"agentid\":" + "\"" + "1000002" + "\",");
sb.append("\"text\":" + "{");
sb.append("\"content\":" + "\"" + content + "\"},");
sb.append("\"debug\":" + "\"" + "1" + "\"");
sb.append("}");
// 請求鏈接
String url = CREATE_SESSION_URL + ACCESS_TOKEN;
PostMethod post = new PostMethod(url);
post.releaseConnection();
post.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 設置策略,防止報cookie錯誤
DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
// 給post設置參數
post.setRequestBody(sb.toString());
String result = "";
try {
client.executeMethod(post);
result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
post.releaseConnection();
return result;
}
/**
* 此方法可以發送任意類型消息
*
* @param msgType
* text|image|voice|video|file|news
* @param touser
* 成員ID列表(消息接收者,多個接收者用‘|’分隔,最多支持1000個)。特殊情況:指定為@all,
* 則向關注該企業應用的全部成員發送
* @param toparty
* 部門ID列表,多個接收者用‘|’分隔,最多支持100個。當touser為@all時忽略本參數
* @param totag
* 標簽ID列表,多個接收者用‘|’分隔。當touser為@all時忽略本參數
* @param content
* msgType=text時 ,文本消息內容
* @param mediaId
* msgType=image|voice|video時 ,對應消息信息ID(--------)
* @param title
* msgType=news|video時,消息標題
* @param description
* msgType=news|video時,消息描述
* @param url
* msgType=news時,消息鏈接
* @param picurl
* msgType=news時,圖片路徑
* @param safe
* 表示是否是保密消息,0表示否,1表示是,默認0
*/
public void sendWeChatMsg(String msgType, String touser, String toparty, String totag, String content, String mediaId, String title,
String description, String url, String picurl, String safe) {
URL uRl;
String ACCESS_TOKEN = getAccessToken();
// 拼接請求串
String action = CREATE_SESSION_URL + ACCESS_TOKEN;
// 封裝發送消息請求json
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"touser\":" + "\"" + touser + "\",");
sb.append("\"toparty\":" + "\"" + toparty + "\",");
sb.append("\"totag\":" + "\"" + totag + "\",");
if (msgType.equals("text")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"text\":" + "{");
sb.append("\"content\":" + "\"" + content + "\"");
sb.append("}");
} else if (msgType.equals("image")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"image\":" + "{");
sb.append("\"media_id\":" + "\"" + mediaId + "\"");
sb.append("}");
} else if (msgType.equals("voice")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"voice\":" + "{");
sb.append("\"media_id\":" + "\"" + mediaId + "\"");
sb.append("}");
} else if (msgType.equals("video")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"video\":" + "{");
sb.append("\"media_id\":" + "\"" + mediaId + "\",");
sb.append("\"title\":" + "\"" + title + "\",");
sb.append("\"description\":" + "\"" + description + "\"");
sb.append("}");
} else if (msgType.equals("file")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"file\":" + "{");
sb.append("\"media_id\":" + "\"" + mediaId + "\"");
sb.append("}");
} else if (msgType.equals("news")) {
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"news\":" + "{");
sb.append("\"articles\":" + "[");
sb.append("{");
sb.append("\"title\":" + "\"" + title + "\",");
sb.append("\"description\":" + "\"" + description + "\",");
sb.append("\"url\":" + "\"" + url + "\",");
sb.append("\"picurl\":" + "\"" + picurl + "\"");
sb.append("}");
sb.append("]");
sb.append("}");
}
sb.append(",\"safe\":" + "\"" + safe + "\",");
sb.append("\"agentid\":" + "\"" + "1000002" + "\",");
sb.append("\"debug\":" + "\"" + "1" + "\"");
sb.append("}");
String json = sb.toString();
try {
uRl = new URL(action);
HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//
// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //
// 讀取超時30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 傳入參數
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("請求返回結果:" + result);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 企業接口向下屬關注用戶發送微信消息(實現方式二)
*
* @param touser
* 成員ID列表(消息接收者,多個接收者用‘|’分隔,最多支持1000個)。特殊情況:指定為@all,
* 則向關注該企業應用的全部成員發送
* @param toparty
* 部門ID列表,多個接收者用‘|’分隔,最多支持100個。當touser為@all時忽略本參數
* @param totag
* 標簽ID列表,多個接收者用‘|’分隔。當touser為@all時忽略本參數
* @param content
* 消息內容
* @param safe
* 消息是否保密
* @return
*/
public void sendWeChatMsgText(String touser, String toparty, String totag, String content, String safe) {
URL uRl;
String ACCESS_TOKEN = getAccessToken();
// 拼接請求串
String action = CREATE_SESSION_URL + ACCESS_TOKEN;
// 封裝發送消息請求json
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"touser\":" + "\"" + touser + "\",");
sb.append("\"toparty\":" + "\"" + toparty + "\",");
sb.append("\"totag\":" + "\"" + totag + "\",");
sb.append("\"msgtype\":" + "\"" + MSGTYPE + "\",");
sb.append("\"text\":" + "{");
sb.append("\"content\":" + "\"" + content + "\"");
sb.append("}");
sb.append(",\"safe\":" + "\"" + safe + "\",");
sb.append("\"agentid\":" + "\"" + "1000002" + "\",");
sb.append("\"debug\":" + "\"" + "1" + "\"");
sb.append("}");
String json = sb.toString();
System.out.println("==========================");
System.out.println(json);
System.out.println("==========================");
try {
uRl = new URL(action);
HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//
// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //
// 讀取超時30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 傳入參數
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("請求返回結果:" + result);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SendWeChatMessage weChat = new SendWeChatMessage();
weChat.sendWeChatMsgText("ChengXueFeng", "1", "", "微信測試", "0");
// weChat.sendWeChatMsg("text", "mxlydx", "4", "", "測試senMsg", "", "",
// "", "", "", "0");
// weChat.sendWeChatMessage("mxlydq", "2", "", "Hi");
}
轉自:https://www.jianshu.com/p/b0b81a986e35
