主动发送消息image
企业微信api
企业号开发者接口文档
企业微信接口调试工具
微信企业号错误代码查询工具
前言
主动发送消息,根据发送消息类型不同分为2类,一类:简单信息例如文本类,只需要获取acces_token后,直接编辑文本信息发送给微信服务器即可到达我们关注的微信企业号;二类:稍微复杂信息如图片,需要先获取acces_token后,再发送图片的url,类型,acces_token,获取media_id,之后再发送给企业号;大致原理如此;整个初级项目(其中的各种id需要填入自己的,我的是测试企业号):在百度云连接里
直接上代码
代码中将常用操作抽离成方法,需要时直接调用;
一下是主题代码:主要是调用各种类型的信息的,目前只写了这几个;
package com.wxwork1;
import com.wxwork.networkcode.MediaUploadUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestAccessToken3 {
/**
* 程序入口:调用各种方法
*/
public static void main(String[] args) {
// 发送 GET 请求
String corpid = " ";
String corpsecret = " ";
String access_token = WxworkUtil.GetForAT(corpid, corpsecret).get("access_token");
System.out.println("access_token:" + access_token);
// 获取accestoken后,发送post请求,目前发送txt格式,发送的参数为json格式
JSONObject jsparam = new JSONObject();
JSONObject jsparam2 = new JSONObject();
String words = "image";
if (("text").equals(words)) {//发送文本信息
jsparam.put("content",
"你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。");
jsparam2.put("touser", "@all");
jsparam2.put("msgtype", "text");
jsparam2.put("agentid", 1000002);
jsparam2.put("text", jsparam);
jsparam2.put("safe", "0");
} else if (("textcard").equals(words)) {//发送文本卡片信息
jsparam.put("title", "测试通知--测试标题长度4汉字");
jsparam.put("description",
"<div class=\"gray\">2018年1月10日</div> <div class=\"normal\">恭喜你,成功测试文本卡片信息,同时测试文本长度,1234567890</div><div class=\"highlight\">请于2018年1月11日前联系行政同事领取</div>");
jsparam.put("url", "https://www.zhihu.com/signup?next=%2F");
jsparam.put("btntxt", "更多的信息和数据--测试超过4汉字");
jsparam2.put("textcard", jsparam);
jsparam2.put("msgtype", "textcard");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
} else if (("image").equals(words)) {//发送照片信息
String result = MediaUploadUtil.uploadMedia(access_token,"image",
"https://work.weixin.qq.com/wework_admin/frame#material/image");
System.out.println(result);
jsparam.put("media_id", WxworkUtil.readRuslt(result).get("media_id"));
jsparam2.put("image", jsparam);
jsparam2.put("msgtype", "image");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
jsparam2.put("safe", "0");
} else if (("news").equals(words)) {
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
jsonObject1.put("title", "图文消息测试-----字数测试");
jsonObject1.put("description", "图像消息--详细信息展示或者描述");
jsonObject1.put("url", "https://www.zhihu.com/signup?next=%2F");
jsonObject1.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/imagemsg.jpeg");
jsonObject1.put("btntxt", "更多信息");
jsonObject2.put("title", "图文消息测试-----字数测试");
jsonObject2.put("description", "图像消息--详细信息展示或者描述");
jsonObject2.put("url", "");
jsonObject2.put("picurl","http://img15.3lian.com/2015/c1/83/d/34.jpg");
jsonObject2.put("btntxt", "更多信息");
jsonObject3.put("title", "图文消息测试-----字数测试");
jsonObject3.put("description", "图像消息--详细信息展示或者描述");
jsonObject3.put("url", "");
jsonObject3.put("picurl", "http://img15.3lian.com/2015/c1/83/d/30.jpg");
jsonObject3.put("btntxt", "更多信息");
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);
jsparam2.put("news", jsonArray);
jsparam2.put("msgtype", "news");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
}
String sendruslt = WxworkUtil.sendData(access_token, jsparam2).get("access_token");
System.out.println("post请求返回结果:" + sendruslt);
}
}
一下是自己抽离的方法(假装是工具类):
package com.wxwork1;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wxwork.networkcode.MediaUtil;
import net.sf.json.JSONObject;
/**
* 编写工具类:
* 1.readRuslt(String string):
* 解析微信公众号返回数据,判断请求成功,成功标志:errcode:0,返回的的acces_token秘钥,素材id,等等
* 2.GetForAT(String corpid,String corpsecret):
* 发送get请求
* 3.sendData(String access_token,JSONObject jsparam):
* 发送post请求
* 4.uploadMedia(String accessToken, String type, String mediaFileUrl)
* 上传素材,mediaFileUrl是http的网址格式,本地格式为解析;
* 5.getFileEndWitsh(String contentType)
* 根据内容类型判断文件扩展名
*/
public class WxworkUtil {
/**
* 编写工具类:
* 1.readRuslt(String string):
* 解析微信公众号返回数据,判断请求成功,成功标志:errcode:0,返回的的acces_token秘钥,素材id,等等
*/
public static Map<String, String> readRuslt(String string){
Map<String, String> teMap = new HashMap<>();
String[] ss = string.substring(1, string.length()-1).split(",");
List<String> ls = Arrays.asList(ss);
System.out.println(Arrays.toString(ss));
for(String temp:ls){
teMap.put(temp.split(":")[0].replaceAll("\"",""), temp.split(":")[1].replaceAll("\"",""));
}
return teMap;
}
/*** 2.GetForAT(String corpid,String corpsecret):
* 发送get请求
*/
public static Map<String, String> GetForAT(String corpid,String corpsecret) {
String result = null;
BufferedReader in = null;
try {
String urlNameString = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid
+ "&corpsecret=" + corpsecret;
URL realUrl = new URL(urlNameString);
System.out.println(realUrl);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Content-Type", "appliction/json;charset=UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//http请求属性
System.out.println("http请求属性:"+connection.getRequestProperty("Content-Type"));
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println("http响应头文件:"+key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result=line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
//maps = readRuslt(result);
return readRuslt(result);
}
/*** 3.sendData(String access_token,JSONObject jsparam):
* 发送post请求
*/
public static Map<String, String> sendData(String access_token,JSONObject jsparam){
String url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
PrintWriter out = null;
BufferedReader in = null;
String result = "";
System.out.println("post请求josn串:"+jsparam.toString());
try {
URL realUrl = new URL(url);
System.out.println("post请求地址:"+realUrl);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-Type", "appliction/json;charset=UTF-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(jsparam);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
//System.out.println(result.toString());
return readRuslt(result);
}
/**
* 上传媒体文件
* @param accessToken 接口访问凭证
* @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
* @param media form-data中媒体文件标识,有filename、filelength、content-type等信息
* @param mediaFileUrl 媒体文件的url
* 上传的媒体文件限制
* 图片(image):1MB,支持JPG格式
* 语音(voice):2MB,播放长度不超过60s,支持AMR格式
* 视频(video):10MB,支持MP4格式
* 普通文件(file):10MB
* */
public static String uploadMedia(String accessToken, String type, String mediaFileUrl) {
String string = null;
// 拼装请求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = MediaUtil.getFileEndWitsh(contentType);
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
string = jsonObject.toString();
} catch (Exception e) {
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);
}
return string;
}
/**
* 根据内容类型判断文件扩展名
*
* @param contentType 内容类型
* @return
*/
public static String getFileEndWitsh(String contentType) {
String fileEndWitsh = "";
if ("image/jpeg".equals(contentType))
fileEndWitsh = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileEndWitsh = ".mp3";
else if ("audio/amr".equals(contentType))
fileEndWitsh = ".amr";
else if ("video/mp4".equals(contentType))
fileEndWitsh = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileEndWitsh = ".mp4";
return fileEndWitsh;
}
}
不知道是那抄的工具类:
package com.wxwork.networkcode;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
/**
* Description:
* Author:py
*/
public class MediaUploadUtil {
/**
* 上传媒体文件
* @param accessToken 接口访问凭证
* @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
* @param media form-data中媒体文件标识,有filename、filelength、content-type等信息
* @param mediaFileUrl 媒体文件的url
* 上传的媒体文件限制
* 图片(image):1MB,支持JPG格式
* 语音(voice):2MB,播放长度不超过60s,支持AMR格式
* 视频(video):10MB,支持MP4格式
* 普通文件(file):10MB
* */
public static String uploadMedia(String accessToken, String type, String mediaFileUrl) {
String string = null;
// 拼装请求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = MediaUtil.getFileEndWitsh(contentType);
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
string = jsonObject.toString();
} catch (Exception e) {
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);
}
return string;
}
}
还有些,太多了,在百度云连接里