您的位置:首页 > 移动开发 > 微信开发

微信企业号开发笔记——文本信息发送

2016-09-22 12:31 337 查看
首先,我的技术架构是使用SpringMVC+mybatis+mysql+maven,jdk是用的1.7的,接下来我们实现企业号发送文本消息的例子,废话不多说,直接上代码吧:

发送信息父类BaseSendMessage

package com.xp.weixin;
/**
* 发送信息父类
* @author Nick
*
*/
public class BaseSendMessage {

public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getToperty() {
return toparty;
}
public void setToperty(String toperty) {
this.toparty = toperty;
}
public String getTotag() {
return totag;
}
public void setTotag(String totag) {
this.totag = totag;
}
public String getAgentid() {
return agentid;
}
public void setAgentid(String agentid) {
this.agentid = agentid;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public String touser;
public String toparty;
public String totag;
public String agentid;
public String msgtype;

public String toJsonStr(){
StringBuffer jsonStr = new StringBuffer("{");
StringBuffer str_tmp = new StringBuffer();
if(null !=touser && !"".equals(touser)){
if(!"".equals(str_tmp.toString())){//如果不为空
str_tmp.append(",");
}
str_tmp.append( "\touser\": \""+touser+"\"");
}
if(null!=toparty&&!"".equals(toparty)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"toparty\": \""+toparty+"\"");
}
if(null!=totag&&!"".equals(totag)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"totag\": \""+totag+"\"");
}
if(null!=msgtype&&!"".equals(msgtype)){
//去除空格
msgtype=msgtype.trim();
//判断是否加逗号
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"msgtype\": \""+msgtype+"\"");
//新闻消息

}
if(null!=agentid&&!"".equals(agentid)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"agentid\": \""+agentid+"\"");
}

jsonStr.append(str_tmp).append("}");
return jsonStr.toString();
}

}
WxInterface 测试微信企业号发送类
package com.xp.weixin;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

/**
* WxInterface 测试微信企业号发送类
* @author Nick
*
*/
public class WxInterfaces {
public static String access_token;
public static Date access_token_date;

public static void main(String[] args) {
WxInterfaces wxi = new WxInterfaces();
System.out.println(wxi.getToken());
WxTextMessage text = new WxTextMessage();
text.setAgentid("2");
text.setMsgtype("text");
text.setTouser("@all");
text.setContent("文本信息再次发送成功");
wxi.sendMessage(text);
System.out.println(JSONObject.fromObject(text));
System.out.println(wxi.sendMessage(text));
}
//获取token
public String getToken(){
String corpid="wx6c01a901ee539038";//获取企业号ID
String corpsecret= "umIb4FE_w17z-9ZbYogGkjpo3mrVSS2pguaMVTDY2Fz33Yj8WAXb_JibGl34y4HT";//获取管理组的秘钥
String token = "";
//1、判断:如果access_token 不存在或者空字符串
//当access_token为空时,当当前时间-请求时间大于微信的规定时间时

if (null==access_token||"".equals(access_token)||(new Date().getTime()-access_token_date.getTime()) > 7200*1000) {
try {
//2、httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
//3、请求
HttpGet httpget = new HttpGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
//Http
//4、返回
ResponseHandler<JSONObject> responseHandler =new ResponseHandler<JSONObject>() {
@Override
public JSONObject handleResponse(final HttpResponse response)throws ClientProtocolException, IOException {
//获取状态码返回status
int status =response.getStatusLine().getStatusCode();
//判断返回状态码
if(status>=200 && status<=300){
HttpEntity entity = response.getEntity();
if (null !=entity) {
String entityStr = EntityUtils.toString(entity);
JSONObject jo = JSONObject.fromObject(entityStr);
return jo;
} else {//如果没有就返回null

return null;
}

}else{
throw new ClientProtocolException("error status"+status);
}

}
};

//5、从请求获取access_token

JSONObject jsonObject = httpclient.execute(httpget,responseHandler);
if(null!=jsonObject){
token=jsonObject.getString("access_token");
}
httpclient.close();//关闭httpclient
access_token=token;
access_token_date =new Date();
} catch (IOException e) {
e.printStackTrace();
}

} else {
token=access_token;
}

return token;
}

//发送信息
public boolean sendMessage(BaseSendMessage message){
boolean flag =false;
//1、消息
String toJsonStr = message.toJsonStr();
//2、token
String token = getToken();
try {
//3、httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
//4、httppost
HttpPost httppost = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token);
StringEntity se = new StringEntity(toJsonStr,ContentType.create("text/plain","UTF-8"));
httppost.setEntity(se);
//5、responsehandler
//、返回
ResponseHandler<JSONObject> responseHandler =new ResponseHandler<JSONObject>() {
@Override
public JSONObject handleResponse(HttpResponse response)throws ClientProtocolException, IOException {
//获取状态码返回status
int status =response.getStatusLine().getStatusCode();
//判断返回状态码
if(status>=200 && status<=300){
HttpEntity entity = response.getEntity();
if (null !=entity) {
String entityStr = EntityUtils.toString(entity);
JSONObject jo = JSONObject.fromObject(entityStr);
return jo;
} else {//如果没有就返回null

return null;
}

}else{
throw new ClientProtocolException("error status"+status);
}

}
};
//6、errcode
int errcode =0;
JSONObject jsonObject = httpClient.execute(httppost,responseHandler);
System.out.println(jsonObject+"你获取的jsonObject值");
if(null!=jsonObject){
errcode =Integer.parseInt(jsonObject.getString("errcode"));
}
if(errcode==0){
flag = true;
}else{

}
} catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}

return flag;
}
}

Text文本信息类--WxTextMessage需要重写BaseSendMessage父类
package com.xp.weixin;
/**
* Text文本信息类
* @author Administrator
*
*/
public class WxTextMessage extends BaseSendMessage{
//
String content;
public WxTextMessage(){};
public WxTextMessage( String touser,String toparty,String totag,String agentid,String msgtype){
super();
super.toparty = toparty;
super.touser = touser;
super.totag = totag;
super.agentid = agentid;
super.msgtype = msgtype;
}

//content的set/get方法
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}

//重写父类toJsonStr方法
public String toJsonStr(){
StringBuffer jsonStr = new StringBuffer("{");
StringBuffer str_tmp = new StringBuffer("");
if(null != touser || "".equals(touser)){
if(!"".equals(str_tmp.toString())){//如果不为空
str_tmp.append(",");
}
str_tmp.append( "\"touser\": \""+touser+"\"");
}
if(null!=toparty&&!"".equals(toparty)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"toparty\" : \""+toparty+"\"");
}
if(null!=totag&&!"".equals(totag)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"totag\": \""+totag+"\"");
}
if(null!=msgtype&&!"".equals(msgtype)){
b0b8

//去除空格
msgtype=msgtype.trim();
//判断是否加逗号
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"msgtype\": \""+msgtype+"\"");
//新闻消息

}
if(null!=agentid&&!"".equals(agentid)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"agentid\": \""+agentid+"\"");
}
if(null!=content&&!"".equals(content)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"text\":{\"content\": \""+content+"\"}");
}

jsonStr.append(str_tmp).append("}");
return jsonStr.toString();
}
}


然后测试直接在WxInterfaces类里测试就好了,看图如下:

这样就可以了,成功的结果如下:

此处为true就是成功了,然后你就可以去看你的手机是否有接到信息了,如在这过程中有遇到什么问题,欢迎加我QQ:542601041,一起交流,希望能帮到大家!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐