[本文所描述的内容具有一定的时效性,请以实际开发所处环境为准]
在前面的几篇文章中,我们已经叙述了,微信企业号中常见功能的实现原理,今天我们按照文章的顺序,给出相应的功能节点的示例代码。但是,对于程序的结构,还请各位看官按照自己的实际需求重新设计,另外,在github上,已经有现成的关于微信开发的开源项目,有兴趣的读者也可以学习一下。
-------------------------------------------------------------------------------------------------------------------------------------
示例环境:
系统:win7 x64
开发工具:myeclipse2014
开发语言:java JDK1.7
示例1.建立连接--主动。
【主动建立连接需要有别的动作来实现才能看到效果,因此示例1中,我们以发消息为里说明主动连接的实现效果】
准备工作:
a.参照前文申请一个企业号
b.先登陆微信公众平台手动添加一个用户
c.两个重要参数:corpid,serect
d.json工具包:json-lib-2.3-jdk15.jar,它的依赖包:commons-beanutils-1.7.0.jar,commons-collections-3.2.1.jar,commons-lang-2.5.jar,commons-logging-1.0.4.jar,ezmorph-1.0.6.jar
示例代码如下:
package test;
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;
/**
*@author 作者 E-mail:ingo
*@version 创建时间:2016年1月31日下午4:32:14
*类说明
*/
public class Main {
public static void main(String[] args) {
//企业号id
String corpid = "wxabc591........5";
//企业号密钥
String serect = "QqLOOyGEa.......BXM3B1n43a";
//token获取地址
String accesstokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SERCRET";
accesstokenurl = accesstokenurl.replace("ID", corpid).replace("SERCRET", serect);
//获取token
JSONObject accesstoken = HttpRequest(accesstokenurl,"GET",null);
String token = accesstoken.getString("access_token");
//消息发送接口地址
String posturl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
posturl = posturl.replace("ACCESS_TOKEN", token);
//消息内容
String postdata = STextMsg("ingo", "", "", "12", "test");
//发送消息
JSONObject result = HttpRequest(posturl,"GET",postdata);
//结果输出
System.out.println(result);
}
/**
* text消息
* @param touser UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送————"touser": "UserID1|UserID2|UserID3"
* @param toparty PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数————"toparty": " PartyID1 | PartyID2 "
* @param totag TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数————"totag": " TagID1 | TagID2 "
* @param msgtype 消息类型,此时固定为:text
* @param agentid 企业应用的id,整型。可在应用的设置页面查看
* @param content 消息内容
* @param safe 表示是否是保密消息,0表示否,1表示是,默认0
* */
public static String STextMsg(String touser,String toparty,String totag,String agentid,String content){
String PostData = "{\"touser\": \"%s\",\"toparty\": \"%s\",\"totag\": \"%s\",\"msgtype\": \"text\",\"agentid\":\"%s\",\"text\": {\"content\": \"%s\"},\"safe\":\"0\"}";
return String.format(PostData, touser,toparty,totag,agentid,content);
}
public static JSONObject HttpRequest(String requestUrl, String requestMethod,
String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
OutputStream out = null;
InputStream input = null;
InputStreamReader inputReader = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
// 建立连接
URL url = new URL(requestUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置http头部信息
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestMethod);
// 写入消息实体
if (outputStr != null) {
out = connection.getOutputStream();
out.write(outputStr.getBytes("UTF-8"));
}
// 流处理
input = connection.getInputStream();
inputReader = new InputStreamReader(input, "UTF-8");
reader = new BufferedReader(inputReader);
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String re = buffer.toString();
jsonObject = JSONObject.fromObject(re);
} catch (Exception e) {
//日志处理等,请自行实现
e.printStackTrace();
} finally {
try {
if (outputStr != null) {
out.close();
}
// 关闭连接、释放资源
if (reader != null) {
reader.close();
}
if (inputReader != null) {
inputReader.close();
}
if (input != null) {
input.close();
}
input = null;
connection.disconnect();
} catch (Exception e) {
//日志处理等,请自行实现
e.printStackTrace();
}
}
return jsonObject;
}
}
运行结果:
{"errcode":0,"errmsg":"ok"}
package test;
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;
/**
*@author 作者 E-mail:ingo
*@version 创建时间:2016年1月31日下午4:32:14
*类说明
*/
public class Main {
public static void main(String[] args) {
//企业号id
String corpid = "wxabc......d5";
//企业号密钥
String serect = "QqLOO......M3B1n43a";
//token获取地址
String accesstokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SERCRET";
accesstokenurl = accesstokenurl.replace("ID", corpid).replace("SERCRET", serect);
//获取token
JSONObject accesstoken = HttpRequest(accesstokenurl,"GET",null);
String token = accesstoken.getString("access_token");
String filePath = "http://img4.imgtn.bdimg.com/it/u=805849949,3076359299&fm=206&gp=0.jpg";
//上传素材文件
JSONObject result = uploadMedia(token, "image", filePath);
System.out.println(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):20MB
* */
public static JSONObject uploadMedia(String accessToken, String type, String mediaFileUrl) {
JSONObject jsonObject = 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.getContentType();
// 根据内容类型判断文件扩展名
String fileExt = ".jpg";
// 请求体开始
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.fromObject(buffer.toString());
} catch (Exception e) {
//日志处理等,请自行完善。
}
return jsonObject;
}
public static JSONObject HttpRequest(String requestUrl, String requestMethod,
String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
OutputStream out = null;
InputStream input = null;
InputStreamReader inputReader = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
// 建立连接
URL url = new URL(requestUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置http头部信息
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestMethod);
// 写入消息实体
if (outputStr != null) {
out = connection.getOutputStream();
out.write(outputStr.getBytes("UTF-8"));
}
// 流处理
input = connection.getInputStream();
inputReader = new InputStreamReader(input, "UTF-8");
reader = new BufferedReader(inputReader);
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String re = buffer.toString();
jsonObject = JSONObject.fromObject(re);
} catch (Exception e) {
//日志处理等,请自行实现
e.printStackTrace();
} finally {
try {
if (outputStr != null) {
out.close();
}
// 关闭连接、释放资源
if (reader != null) {
reader.close();
}
if (inputReader != null) {
inputReader.close();
}
if (input != null) {
input.close();
}
input = null;
connection.disconnect();
} catch (Exception e) {
//日志处理等,请自行实现
e.printStackTrace();
}
}
return jsonObject;
}
}
运行结果:
{"type":"image","media_id":"1RlmNyD4bntO_v_XMBBH_1ACSQkcFBWt3-UCj_TeN2nU8d28LQ-j406IUPTbv1VAZnU5DCVLkXoDHEQDp2kIYTQ","created_at":1454291860}
public class Button {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class CommonButton extends Button{
private String type;
private String key;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
public class ViewButton extends Button{
private String type;
private String url;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
public class BaseMenu extends Button {
private Button[] sub_button;
public Button[] getSub_button() {
return sub_button;
}
public void setSub_button(Button[] sub_button) {
this.sub_button = sub_button;
}
}
public String create_JSONMenu(String agentid,BaseMenu bm1,BaseMenu bm2,BaseMenu bm3){
Menu menu = new Menu();
MenuArray ma = new MenuArray();
ma.setSub_BaseMenu(new BaseMenu[]{bm1,bm2,bm3});
ma = mAisNull(ma);
switch(ma.getSub_BaseMenu().length){
case 1:menu.setButton(new Button[] { isOnly(isFull(ma.getSub_BaseMenu()[0]))});break;
case 2:menu.setButton(new Button[] { isOnly(isFull(ma.getSub_BaseMenu()[0])),isOnly(isFull(ma.getSub_BaseMenu()[1]))});break;
case 3:menu.setButton(new Button[] { isOnly(isFull(ma.getSub_BaseMenu()[0])),isOnly(isFull(ma.getSub_BaseMenu()[1])),isOnly(isFull(ma.getSub_BaseMenu()[2]))});break;
}
String jsonMenu = JSONObject.fromObject(menu).toString();
System.out.println("jsonMenu--"+jsonMenu);
String Postjson = "{\"msgType\":\"menu\",\"group\":\"create\",\"content\":{\"agentid\":\"%s\",\"menu\":%s}}";
Postjson = String.format(Postjson,agentid, jsonMenu);
return Postjson;
}
public class Menu {
private Button[] button;
public Button[] getButton() {
return button;
}
public void setButton(Button[] button) {
this.button = button;
}
}
public class MenuArray extends BaseMenu {
private BaseMenu[] sub_BaseMenu;
public BaseMenu[] getSub_BaseMenu() {
return sub_BaseMenu;
}
public void setSub_BaseMenu(BaseMenu[] sub_BaseMenu) {
this.sub_BaseMenu = sub_BaseMenu;
}
}
public MenuArray mAisNull(MenuArray ma){
List menuArray = new ArrayList();
BaseMenu [] bms = ma.getSub_BaseMenu();
for(BaseMenu bm:bms){
if(bm.getSub_button()[0]!=null){
menuArray.add(bm);
}
}
ma.setSub_BaseMenu(menuArray.toArray(new BaseMenu[0]));
return ma;
}
public void main(String[] args){
CommonButton btn11 = create_Common_Button("测试菜单-11","1");
CommonButton btn12 = create_Common_Button("测试菜单-12","2");
CommonButton btn13 = create_Common_Button("测试菜单-13","3");
CommonButton btn14 = create_Common_Button("测试菜单-14","4");
CommonButton btn15 = create_Common_Button("测试菜单-15","5");
ViewButton btn21 = create_View_Button("链接菜单-1", "http://baidu.com");
ViewButton btn22 = create_View_Button("链接菜单-2", "http://baidu.com");
ViewButton btn25 = create_View_Button("链接菜单-3", "http://baidu.com");
BaseMenu bb1 = create_BaseButton("一级菜单-1",btn11, btn12, btn13,btn14,btn15);
BaseMenu bb2 = create_BaseButton("二级菜单-2",btn21, null, null,null,null);
BaseMenu bb3 = create_BaseButton("三级菜单-3",btn22, null, null,null,null);
String menu = create_JSONMenu("9",bb1, bb2, bb3);//menu代表已经组装好的数据。
//请自行查阅菜单创建接口地址,上传方式
//发送函数见上文,这里不再重复
}
-------------------------------------------------------------------------------------------------------------------------------------
至此,微信企业号开发(8)--示例代码结束
备注:
1.微信企业号开发的基本内容到此结束,其他内容的实现请读者参考官方文档来实现。
2.由于开发文档处于变动之中,请读者们一定按照最新的文档进行开发,上文仅供参考。
参考资料:
微信公众平台开发者文档:http://mp.weixin.qq.com/wiki/home/index.html