Java微信开发一(通过java程序连接微信公众平台)

建立项目:



 

创建WxServlet.java

 

package com.zzhw;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.print.attribute.standard.MediaSize.Other;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.DocumentException;


/**
 * 接入
 * @author Administrator
 *
 */
public class WxServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置字符集
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		//获取输出
		 PrintWriter out = resp.getWriter();
		//接入 调用方法 处理接入
		connect(req,out);
		
	}
	
	
	/*
	 *接收数据
	 * 
	 *  
	 *  */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置字符集
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		//回送信息
		echoMsg(req,resp);
	}
	
	
	
	/*
	 * 自动回复消息
	 * 1、获取xml数据
	 * 2、xml-->解析-->存放map中(map中方的是xml数据)
	 * 3.把xml数据解析转化成对象
	 * 4、将对象中的属性from<--->to调换位置,更改时间,内容
	 * 5、将对象再转为xml
	 * 6、resp发送出去
	 */
	
	
	
	private void echoMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		
			PrintWriter writer = resp.getWriter();
			Map<String, String> xmlMap=null;
			
			try {
				// 2、xml-->解析-->存放map中(map中方的是xml数据)
				xmlMap = MessageUtil.toMap(req.getInputStream());
				// 3.把xml数据解析转化成对象 
				Message message = MessageUtil.toMessage(xmlMap);
				
				//4、将对象中的属性from<--->to调换位置,更改时间,内容
				
				String from = message.getFromUserName();
				String to = message.getToUserName();
				message.setFromUserName(to);
				message.setToUserName(from);
				
				message.setCreateTime(System.currentTimeMillis());
				
				
				String content = message.getContent();
				
				content=null==content?"":content.trim();
				
				//书写返回数据
				String reply = "";
				//获取消息类型
				String type=xmlMap.get("MsgType");
				//比较
				if(type.equals(MessageType.TEXT)){
					if(content.equals("1")||content.equalsIgnoreCase("hw")){
						reply = hwTxt();
						
					}else if(content.equals("2")||content.equalsIgnoreCase("hw")){
						reply = jokeTxt();
						
					}else if(content.equals("?")||content.equals("?")){
						reply = mainMenu();
					}else {
						//如果其他消息
						reply = Other(content);
					}
				}else if(type.equals(MessageType.EVENT)){
					//获取事件类型
					String eventType = xmlMap.get("Event").toLowerCase();
					if(eventType.equals(MessageType.SUBSCRIBE)){
						//关注事件
						reply = mainMenu();
						message.setMsgType(MessageType.TEXT);
						
					}else if(eventType.equals(MessageType.UNSUBSCRIBE)){
						System.out.println("有人退出了!");
					}
				}
				//设置回送信息
				message.setContent(reply);
				//将message对象转化为xml
				String xmlStr = MessageUtil.toXml(message);
				System.out.println(xmlStr);
				//使用write对象发送出去
				writer.print(xmlStr);
				writer.flush();
			} catch (DocumentException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	
	}
   //天气查询
//   private String weather(String content) {
//		content = content.replace("市", "");
//		//获取天气字符串
//		String weatherStr = WeatherUtil.getWeather(content);
//		//处理null;
//		if(null==weatherStr||(weatherStr=weatherStr.trim()).equals("")){
//			return Other(content);
//			
//		}
//		return null;
//	}


private String Other(String content) {
	// TODO Auto-generated method stub
	return "---------->" + content;
}


private String mainMenu() {
	   StringBuffer buffer = new StringBuffer();
		buffer.append("欢迎关注秋露LivingMuseum,请按以下提示进行操作:\n");
		buffer.append("1、导航菜单\n");
		buffer.append("2、笑话\n");
		buffer.append("3、欢迎\n");
		buffer.append("4、欢迎\n");
		buffer.append("5、热烈欢迎!\n");
		buffer.append("回复?显示此帮助菜单!\n");
		return buffer.toString();
	}


/*
    * 笑话集合
    */
	
	private String jokeTxt() {
		StringBuffer buffer = new StringBuffer();
		Joke joke = JokeUtil.getDefaultJokeList();
		String title = joke.getTitle();
		String content = joke.getText();
		if(null!=title){
			title=title.trim();
			
			buffer.append(title+"\n");
		}
		if(null!=content){
			content=content.trim();
			
			buffer.append(content);
		}
		
		return buffer.toString();   
	}


	private String hwTxt() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("秋露商城\n");
		buffer.append("1、秋露商城\n");
		buffer.append("2、秋露商城\n");
		buffer.append("3、秋露商城\n");
		buffer.append("4、秋露商城\n");
		buffer.append("5、还是秋露商城\n");
		buffer.append("欢迎访问秋露商城!\n");
		return buffer.toString();
	} 


	/*
	 * 接入
	 */

	private void connect(HttpServletRequest req,PrintWriter out) {
		//获取参数
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		
		//校验
		List<String> list = new ArrayList<String>();
		list.add("zzhw");//token
		list.add(timestamp);
		list.add(nonce);
		//排序
		Collections.sort(list);
		//拼接字符串-->shal加密
		StringBuffer buffer = new StringBuffer();
		for(String string : list){
			buffer.append(string);
		}
		//使用apache commons codec 加密
		String shalStr = DigestUtils.shaHex(buffer.toString());
		//对比
		boolean flag = shalStr.equals(signature);
		if(flag){
			System.out.println("恭喜接入成功!");
			out.print(echostr);
			out.flush();
			
		}
		
		
	}
     
}

这里要特别注意在代码222行中:list.add("zzhw");//token

 

zzhw是要在你的微信公众平台上填写的token!!!


配置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>wk_weixin</display-name>
	<servlet>
	<servlet-name>Wx</servlet-name>
	<servlet-class>com.zzhw.WxServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	<servlet-name>Wx</servlet-name>
	<url-pattern>/wx</url-pattern>
	</servlet-mapping>
	
  <welcome-file-list>
    <welcome-file>user.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

部署启动wk_weixin
准备外网映射工具:ngrok。作用:ngrok 是一个反向代理,通过在公共的端点和本地运行的 Web 服务器之间建立一个安全的通道。简单可以理解为经本地的web项目映射到外网上。

ngrok工具下载

     启动ngrok,直接双击startup.bat

 

运行结果如下:

 

 

 

 

登陆微信公众平台,

 

打开基本配置,点击修改配置,填写url和token


这里的url中间填写的就是上面用ngrok映射到本地ip的域名,wk_weixin是myeclipse中的项目名,wx为web.xml中配置的请求。

 

填写完成之后点击提交

控制台打印信息:恭喜接入成功!


 

附:

package com.howin.weixin.servlet;

public class Message {
	
	private String ToUserName;
	
	private String FromUserName;
	
	private long CreateTime;
	
	private String MsgType;
	
	private String Content;
	
	private String MsgId;
	
	public Message(){ 
		
	}

	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 long getCreateTime() {
		return CreateTime;
	}

	public void setCreateTime(long createTime) {
		CreateTime = createTime;
	}

	public String getMsgType() {
		return MsgType;
	}

	public void setMsgType(String msgType) {
		MsgType = msgType;
	}

	public String getContent() {
		return Content;
	}

	public void setContent(String content) {
		Content = content;
	}

	public String getMsgId() {
		return MsgId;
	}

	public void setMsgId(String msgId) {
		MsgId = msgId;
	}



}


 

package com.howin.weixin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;


public class MessageUtil {
	
	public static Map<String, String> toMap(InputStream is) throws DocumentException, IOException{
		 
		SAXReader reader = new SAXReader();
		
		Document doc = reader.read(is);
		
		Element root = doc.getRootElement();
		
		List<Element> elements = root.elements();
		
		Map<String, String> map = new HashMap<String, String>();
		for(Element e:elements){
			map.put(e.getName(), e.getText());
		}
		is.close(); 
		return map;
	}

	/*
	 * 将Map中的数据封装成Message
	 */
	public static Message toMessage(Map<String, String> map){
		Message message = new Message();
		
		message.setMsgType("transfer_customer_service");
		message.setFromUserName(map.get("FromUserName"));
		message.setToUserName(map.get("ToUserName"));
		message.setCreateTime(Integer.valueOf(map.get("CreateTime")));
		message.setMsgId(map.get("MsgId"));
		message.setContent(map.get("Content"));
		return message;
		
	}
	/*
	 * 使用XStream将Message转成Xml
	 * 
	 */
	public static String toXml(Message message){
		//实例化XStream
		XStream stream = new XStream();
		//使用别名作为根元素,否则根元素为保密,类名即替换根元素名称
		stream.alias("xml", message.getClass());
		//转成xml
		return stream.toXML(message);
		
	}
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值