Java实现微信公众平台开发项目源码
Java实现微信公众平台开发项目源码本文向大家介绍使用Java来实现微信公共平台功能,实现根据回复的内容返回对应的消息。供大家学习使用。
微信服务端收发消息接口:WechatServlet.java
package demo.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import demo.process.WechatProcess;
import demo.util.SHA1;
/**
* 微信服务端收发消息接口
*
* @author 科帮网
*
*/
@SuppressWarnings("serial")
public class WechatServlet extends HttpServlet {
// 自定义 token
private String TOKEN = "52itstyle";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String signature = request.getParameter("signature"); // 随机字符串
String echostr = request.getParameter("echostr"); // 时间戳
String timestamp = request.getParameter("timestamp"); // 随机数
String nonce = request.getParameter("nonce");
String[] str = { TOKEN, timestamp, nonce };
Arrays.sort(str); // 字典序排序
String bigStr = str + str + str; // SHA1加密
String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();
// 确认请求来至微信
if (digest.equals(signature)) {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
/** 读取接收到的xml消息 */
StringBuffer sb = new StringBuffer();
InputStream is = request.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据
String result = "";
/** 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回 */
if (echostr != null && echostr.length() > 1) {
result = echostr;
} else {
//正常的微信处理流程
result = new WechatProcess().processWechatMag(xml);
}
System.out.println("说的什么"+result);
response.getWriter().print(result);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
接收到的微信xml实体类:ReceiveXmlEntity.java
package demo.entity;
/**
* 接收到的微信xml实体类
* @author 科帮网
*
*/
public class ReceiveXmlEntity {
private String ToUserName="";
private String FromUserName="";
private String CreateTime="";
private String MsgType="";
private String MsgId="";
private String Event="";
private String EventKey="";
private String Ticket="";
private String Latitude="";
private String Longitude="";
private String Precision="";
private String PicUrl="";
private String MediaId="";
private String Title="";
private String Description="";
private String Url="";
private String Location_X="";
private String Location_Y="";
private String Scale="";
private String Label="";
private String Content="";
private String Format="";
private String Recognition="";
public String getRecognition() {
return Recognition;
}
public void setRecognition(String recognition) {
Recognition = recognition;
}
public String getFormat() {
return Format;
}
public void setFormat(String format) {
Format = format;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getLocation_X() {
return Location_X;
}
public void setLocation_X(String locationX) {
Location_X = locationX;
}
public String getLocation_Y() {
return Location_Y;
}
public void setLocation_Y(String locationY) {
Location_Y = locationY;
}
public String getScale() {
return Scale;
}
public void setScale(String scale) {
Scale = scale;
}
public String getLabel() {
return Label;
}
public void setLabel(String label) {
Label = label;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
public String getEventKey() {
return EventKey;
}
public void setEventKey(String eventKey) {
EventKey = eventKey;
}
public String getTicket() {
return Ticket;
}
public void setTicket(String ticket) {
Ticket = ticket;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getPrecision() {
return Precision;
}
public void setPrecision(String precision) {
Precision = precision;
}
public String getEvent() {
return Event;
}
public void setEvent(String event) {
Event = event;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
}
调用图灵机器人api接口,获取智能回复内容 TulingApiProcess.java
package demo.process;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 调用图灵机器人api接口,获取智能回复内容
* @author 科帮网
*
*/
public class TulingApiProcess {
/**
* 调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果
* @param content
* @return
*/
public String getTulingResult(String content){
/** 此处为图灵api接口,参数key需要自己去注册申请 */
String apiUrl = "http://www.tuling123.com/openapi/api?key=2a31b2f601f74b54ea13db1c82fe5d71&info=";
String param = "";
try {
param = apiUrl+URLEncoder.encode(content,"utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} //将参数转为url编码
/** 发送httpget请求 */
HttpGet request = new HttpGet(param);
String result = "";
try {
HttpResponse response = HttpClients.createDefault().execute(request);
if(response.getStatusLine().getStatusCode()==200){
result = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/** 请求失败处理 */
if(null==result){
return "对不起,你说的话真是太高深了……";
}
try {
JSONObject json = new JSONObject(result);
//以code=100000为例,参考图灵机器人api文档
if(100000==json.getInt("code")){
result = json.getString("text");
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
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">
<servlet>
<servlet-name>WechatServlet</servlet-name>
<servlet-class>demo.servlet.WechatServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WechatServlet</servlet-name>
<url-pattern>/wechat.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
项目源码下载地址:
**** Hidden Message *****
好东西 收下了 哈哈111111111111 好东西 收下了. 有帮助哦。 这个全吗?我也最近在学习微信,先下载下来看看,谢谢分享
看看。 一直想做微信公众平台,但不知道如何入手,真心表示感谢 谢谢 分享。。。。。。。。。。。。。。。。。 谢谢楼主分享源码,共同进步:) 学习一下,谢谢楼主的分享 共享共享感谢