JavaWeb发送信息到微信公众平台的企业号

首先到微信公众平台申请微信企业号: https://qy.weixin.qq.com
申请后须要在管理平台作以下几个步骤:
一、在通信录里添加一个成员并使这个成员关注这个微信企业号;
二、在应用中内心新建一个应用并记录appid;
三、在设置里的权限管理中新建管理组;


新建一个JavaWeb工程并导入以下几个jar文件:
commons-logging-1.1.1.jar,fastjson-1.2.7.jar,httpclient-4.5.1.jar,httpcore-4.4.3.jar,weixin-java-cp-1.3.1.jar

下载jquery-2.1.4.min.js文件并添加到JavaWeb工程中。

JavaWeb工程的代码以下:

AccessToken.java文件内容以下:

package com.shihuan.pojo;

import java.io.Serializable;

public class AccessToken implements Serializable {

private String access_token;
private String expires_in;

public AccessToken() {

}

public String getAccess_token() {
return access_token;
}

public void setAccess_token(String accessToken) {
access_token = accessToken;
}

public String getExpires_in() {
return expires_in;
}

public void setExpires_in(String expiresIn) {
expires_in = expiresIn;
}

}


Text.java文件内容以下:

package com.shihuan.pojo;

import java.io.Serializable;

public class Text implements Serializable {

private String content;

public Text() {

}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}


MsgTypeAndDataFormat.java文件内容以下:

package com.shihuan.pojo;

import java.io.Serializable;

public class MsgTypeAndDataFormat implements Serializable {

private String touser;
private String toparty;
private String totag;
private String msgtype;
private String agentid;
private Text text;
private String safe;

public MsgTypeAndDataFormat() {

}

public String getTouser() {
return touser;
}

public void setTouser(String touser) {
this.touser = touser;
}

public String getToparty() {
return toparty;
}

public void setToparty(String toparty) {
this.toparty = toparty;
}

public String getTotag() {
return totag;
}

public void setTotag(String totag) {
this.totag = totag;
}

public String getMsgtype() {
return msgtype;
}

public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}

public String getAgentid() {
return agentid;
}

public void setAgentid(String agentid) {
this.agentid = agentid;
}

public Text getText() {
return text;
}

public void setText(Text text) {
this.text = text;
}

public String getSafe() {
return safe;
}

public void setSafe(String safe) {
this.safe = safe;
}

}


WeixinCpServlet.java文件内容以下:

package com.shihuan.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.shihuan.pojo.AccessToken;
import com.shihuan.pojo.MsgTypeAndDataFormat;
import com.shihuan.pojo.Text;

public class WeixinCpServlet extends HttpServlet {

protected void doGet(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) throws ServletException, IOException {
System.out.println("doGet...");
paramHttpServletResponse.getWriter().write("WeixinCp doGet!");
paramHttpServletResponse.flushBuffer();
System.out.println("doGet...");
}

protected void doPost(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) throws ServletException, IOException {
System.out.println("doPost...");

String corpid = paramHttpServletRequest.getParameter("corpid");
String corpsecret = paramHttpServletRequest.getParameter("corpsecret");
StringBuilder sb = new StringBuilder();
sb.append("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=").append(corpid).append("&corpsecret=").append(corpsecret);
String getTokenUrl = sb.toString();
HttpPost getTokenUrlPost = new HttpPost(getTokenUrl);
DefaultHttpClient getTokenUrlClient = new DefaultHttpClient();
HttpResponse getTokenUrlResponse = getTokenUrlClient.execute(getTokenUrlPost);
AccessToken atentry = new AccessToken();
if (getTokenUrlResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = getTokenUrlResponse.getEntity();
String jsontext = EntityUtils.toString(entity, "utf-8");
System.out.println(jsontext);
atentry = (AccessToken) JSON.parseObject(jsontext, AccessToken.class);
}

String access_token = atentry.getAccess_token();
System.out.println(access_token);
StringBuilder sbsend = new StringBuilder();
sbsend.append("https://qyapi.weixin.qq.com/cgi-bin/message/send?body=0&access_token=").append(access_token);
String url = sbsend.toString();

String jsonbody = paramHttpServletRequest.getParameter("jsonbody");

Text t = new Text();
t.setContent(jsonbody);

MsgTypeAndDataFormat m = new MsgTypeAndDataFormat();
m.setAgentid("2");
m.setMsgtype("text");
m.setSafe("0");
m.setText(t);
m.setToparty("@all");
m.setTotag("@all");
m.setTouser("@all");

String json = JSON.toJSONString(m);

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);

HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
System.out.println(EntityUtils.toString(entity, "utf-8"));
}

System.out.println("doPost...");
}

public void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse) throws ServletException,IOException {
System.out.println("WeixinCpService...");
super.service(paramServletRequest, paramServletResponse);
paramServletResponse.getWriter().write("WeixinCp service!");
System.out.println("WeixinCpService...");
}

public void init(ServletConfig paramServletConfig) throws ServletException {
super.init(paramServletConfig);
System.out.println("WeixinCpServlet...");
}

public void destroy() {
System.out.println("WeixinServlet[destroy]...");
super.destroy();
}

}


web.xml文件内容以下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>WeixinCp</display-name>

<servlet>
<servlet-name>WeixinCpServlet</servlet-name>
<servlet-class>com.shihuan.servlet.WeixinCpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WeixinCpServlet</servlet-name>
<url-pattern>/weixincp</url-pattern>
</servlet-mapping>


<session-config>
<session-timeout>60</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>


index.html文件内容以下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>weixincp servlet</title>	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">	<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>	<script type="text/javascript">		function sendWxMsg(){			var url = "weixincp";			$.post(url, {corpid:$("#corpid").val(),corpsecret:$("#corpsecret").val(),jsonbody:$("#jsonbody").val()});		}	</script>  </head>  <body>    <form name="frm_data" id="frm_data" method="POST" action="weixincp">	  corpid: <input type="text" id="corpid" name="corpid" value="" size="80px" /><br />	  corpsecret: <input type="text" id="corpsecret" name="corpsecret" value="" size="80px" /><br />	  content: <input type="text" id="jsonbody" name="jsonbody" value="" size="80px" /><br /><br />	  <input type="button" id="sendbtn" name="sendbtn" value="sendWxMsg" onclick="sendWxMsg();" />	</form>  </body></html>
【[color=blue]注[/color]】:附件中是可运行源代码, :arrow: