微信公众号开发1

近期做了微信公众号,所以在此做记录,用的是自己申请测试的公众号,需要域名,所以用的是natapp做内网穿透,后台配置大体上长这样,服务端用的是ssm框架,前端用的jsp,weui

下面的是校验微信公众号的消息类型,和自动回复消息类型

  /**
     * 校验信息是否是从微信服务器发出,处理消息
	 * wx
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/check", method = { RequestMethod.GET, RequestMethod.POST })
    public void check(HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        logger.info("开始校验信息是否是从微信服务器发出");
        // 签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
		if(isGet){
			if (WeiXinUtils.checkSignature(signature, timestamp, nonce)) {
				// 随机字符串
				String echostr = request.getParameter("echostr");
				logger.info("接入成功,echostr "+echostr);
				response.getWriter().write(echostr);
			}
		}else{
			String respMessage = "异常消息!";
			try {
				respMessage = this.weixinPost(request);
				if(respMessage == null){
					respMessage = "";
				}
				response.getWriter().write(respMessage);
				logger.info("The request completed successfully");
				logger.info("to weixin server "+respMessage);
			} catch (Exception e) {
				logger.error("Failed to convert the message from weixin!");
			}
		}
    }


	/**
	 * 处理微信发来的请求
	 *
	 * @param request
	 * @return
	 */
	public String weixinPost(HttpServletRequest request) {
		String respMessage = null;
		try {

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.xmlToMap(request);

			// 发送方帐号(open_id)
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");

			logger.info("FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				//这里根据关键字执行相应的逻辑,只有你想不到的,没有做不到的
//				if(content.equals("xxx")){
//
//				}
//
//				//自动回复
//				TextMessage text = new TextMessage();
//				text.setContent("the text is" + content);
//				text.setToUserName(fromUserName);
//				text.setFromUserName(toUserName);
//				text.setCreateTime(new Date().getTime() + "");
//				text.setMsgType(msgType);
//
//				respMessage = MessageUtil.textMessageToXml(text);
			// 事件推送
			}else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");// 事件类型
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {

					TextMessage text = new TextMessage();
					text.setContent("欢迎关注");
					text.setToUserName(fromUserName);
					text.setFromUserName(toUserName);
					text.setCreateTime(new Date().getTime() + "");
					text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

					respMessage = MessageUtil.textMessageToXml(text);
					// TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
				}else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅

				// 自定义菜单点击事件
				}else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					String eventKey = requestMap.get("EventKey");// 事件KEY值,与创建自定义菜单时指定的KEY值对应
					if (eventKey.equals("customer_telephone")) {
						TextMessage text = new TextMessage();
						text.setContent("");
						text.setToUserName(fromUserName);
						text.setFromUserName(toUserName);
						text.setCreateTime(new Date().getTime() + "");
						text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

						respMessage = MessageUtil.textMessageToXml(text);
					}
				}
			}
		}
		catch (Exception e) {
			logger.error("error......");
		}
		return respMessage;
	}

下面是微信自动回复消息类

import com.ruijie.scp.roomOrder.vo.TextMessage;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageUtil {

    /**
     * 返回消息类型:文本
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";

    /**
     * 返回消息类型:音乐
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

    /**
     * 返回消息类型:图文
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";

    /**
     * 请求消息类型:文本
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";

    /**
     * 请求消息类型:图片
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

    /**
     * 请求消息类型:链接
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";

    /**
     * 请求消息类型:地理位置
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

    /**
     * 请求消息类型:音频
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

    /**
     * 请求消息类型:推送
     */
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";

    /**
     * 事件类型:subscribe(订阅)
     */
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

    /**
     * 事件类型:unsubscribe(取消订阅)
     */
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

    /**
     * 事件类型:CLICK(自定义菜单点击事件)
     */
    public static final String EVENT_TYPE_CLICK = "CLICK";

    /**
     * xml转换为map
     * @param request
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();

        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
            Element root = doc.getRootElement();

            List<Element> list = root.elements();

            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }

            return map;
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }finally{
            ins.close();
        }

        return null;
    }


    /**
     * 文本消息对象转换成xml
     *
     * @param textMessage 文本消息对象
     * @return xml
     */
    public static String textMessageToXml(TextMessage textMessage){
        XStream xstream = new XStream();
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }
}
public class TextMessage {
    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String Content;
    private String 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;
    }

    public String getContent() {
        return Content;
    }

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

    public String getMsgId() {
        return MsgId;
    }

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

上面需要导入jar包,用的是maven,下面的jar用来xmL转文本消息

<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>1.4.9</version>
		</dependency>
		<dependency>
			<groupId>xmlpull</groupId>
			<artifactId>xmlpull</artifactId>
			<version>1.1.3.1</version>
		</dependency>

下面是微信的工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruijie.scp.roomOrder.controller.WeChatConfigController;
import com.ruijie.scp.roomOrder.controller.WeChatController;

import com.ruijie.scp.roomOrder.vo.Template;
import com.ruijie.scp.roomOrder.vo.TemplateParam;
import com.ruijie.scp.util.http.StringUtil;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StreamUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static com.ruijie.scp.util.FileUtil.deleteFile;


public class WeiXinUtils {
    private static final Log logger = LogFactory.getLog(WeiXinUtils.class);
    public static final String APP_ID = "wx2aaf9fdee5d445c0";
    public static final String APP_SECRET = "05b0d018d69e9176fe345042ac6027e4";
    private static String GRANTTYPE2 = "client_credential";// 获取 access-token 的

    private static final Map<String, String> DATA = new HashMap<String, String>();
    private static final char[] CHARS = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    public static final String USE_URI = "http://txutch.natappfree.cc";
    public static final String SNSAPI_BASE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type" +
            "=code&scope=snsapi_base&state=123#wechat_redirect";
    public static final String SNSAPI_USERINFO = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&" +
            "response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    public static final String GET_USERTOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    public static final String GET_USERINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    public static final String CREATE_MENU = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
    public static final String GET_MENU = " https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=";
    //设置所属行业
    public static final String CREATE_INDUSTRY = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=";
    // 此处的token即为微信接口配置填写的签名
    private static final String TOKEN = "weixin";

    private static final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    public static final String ADD_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=";


    /**
     * 设置所属行业
     *
     * @return
     */
    public static String createIndustry() {
        String token = getToken();
        //如果token为空,去微信获取access_token
        String industry = "{\"industry_id1\":\"1\",\"industry_id2\":\"4\"}";
        String result = doPost(CREATE_INDUSTRY + token, industry);
        return result;
    }
    /**
     *获取所属行业
     *
     * @return
     */
    public static String getIndustryType() {
        String templateUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=";
        String token = getToken();
        //如果token为空,去微信获取access_token
        HashMap map = new HashMap();
        String result = doGet(templateUrl + token, map);
        return result;
    }

    /**
     * 获取模板列表
     * @return
     */
    public static String getTemplateList() {
        String templateUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=";
        String token = getToken();
        //如果token为空,去微信获取access_token
        HashMap map = new HashMap();
        String result = doGet(templateUrl + token, map);
        return result;
    }


    /**
     * 设置模板消息
     *
     * @return
     */
    public static Map setTemplate() {
        HashMap mapResult = new HashMap();
        mapResult.put("msg","");
        String resultStr = "";
        String templateUrl = ADD_TEMPLATE_URL;
        String token = getToken();
        //如果token为空,去微信获取access_token
        HashMap mapTemplate = new HashMap();
        mapTemplate.put("template_id_short","OPENTM418251786");
        String templateMsg = JSONObject.toJSONString(mapTemplate);
        String result = doPost(templateUrl + token, templateMsg);
        JSONObject mapResultTemplate1 = JSONObject.parseObject(result);
        if(0 == mapResultTemplate1.getInteger("errcode")){
            mapResult.put("change_template_id",mapResultTemplate1.get("template_id"));
        }else{
            mapResult.put("msg","添加教室调换模板消息失败:原因:"+mapResultTemplate1.getInteger("errmsg")+",");
        }
        mapTemplate.clear();
        mapTemplate.put("template_id_short","OPENTM418249676");
        templateMsg = JSONObject.toJSONString(mapTemplate);
        String result1 = doPost(templateUrl + token, templateMsg);
        JSONObject mapResultTemplate2 = JSONObject.parseObject(result1);
        if(0 == mapResultTemplate2.getInteger("errcode")){
            mapResult.put("order_template_id",mapResultTemplate2.get("template_id"));
        }else{
            resultStr += "教室预约申请模板消息失败:原因:"+mapResultTemplate2.getInteger("errmsg")+",";
            if(StringUtils.isEmpty(String.valueOf(mapResult.get("msg")))){
                mapResult.put("msg",resultStr);
            }else{
                mapResult.put("msg",String.valueOf(mapResult.get("msg")) + resultStr);
            }
        }
        return mapResult;
    }

    /**
     * 发送模板消息
     *
     * @return
     */
    public static String sendTemplateMsg(Template template) {
        String templateUrl = TEMPLATE_URL;
        String token = getToken();
        String result = null;
        result = doPost(templateUrl + token, template.toJSON());
        return result;
    }


    /**
     * 通过appid和secret获取access_token
     *
     * @return access_token
     */
    public static String getToken() {
        String token = DATA.get("access_token");
        //如果token为空,去微信获取access_token
        if (token == null) {
            Map<String, String> param = new HashMap<String, String>();
            param.put("grant_type", "client_credential");
            param.put("appid", String.valueOf(WeChatConfigController.cacheWxMap.get("app_id")));
            param.put("secret", String.valueOf(WeChatConfigController.cacheWxMap.get("app_secret")));
//            param.put("appid", APP_ID);
//            param.put("secret",  APP_SECRET);
            String result = doGet("https://api.weixin.qq.com/cgi-bin/token", param);
            Map map = JSON.parseObject(result, Map.class);
            assert map != null;
            token = (String) map.get("access_token");
            DATA.put("access_token", token);
            //定时删除access_token,expires_in:过期时间
            timedDeletion("access_token", (Integer) map.get("expires_in"));
        }
        return token;
    }

    /**
     * 获取JsapiTicket
     *
     * @return JsapiTicket
     */

    public static String getJsapiTicket() {
        String jsapiTicket = DATA.get("jsapiTicket");
        if (jsapiTicket == null) {
            Map<String, String> param = new HashMap<String, String>();
            param.put("type", "jsapi");
            param.put("access_token", getToken());
            String result = doGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", param);
            Map map = JSON.parseObject(result, Map.class);
            assert map != null;
            jsapiTicket = (String) map.get("ticket");
            DATA.put("jsapiTicket", jsapiTicket);
            timedDeletion("jsapiTicket", (Integer) map.get("expires_in"));
        }
        return jsapiTicket;
    }

    /**
     * 定时删除DATA中的值
     *
     * @param name 要删的值
     * @param time 多久后删除,单位秒
     */
    private static void timedDeletion(final String name, final long time) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(time * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                DATA.remove(name);
            }
        }).start();
    }

    /**
     * 执行get请求
     *
     * @param url 要请求的地址
     * @param param 请求参数
     */
    public static String doGet(String url, Map<String, String> param) {
        // 构造HttpClient的实例
        HttpClient client = new HttpClient();
        StringBuilder stringBuilder = new StringBuilder();
        // 设置httpClient连接主机服务器超时时间:5000毫秒
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        String strParam = "";
        if(param != null && param.size() > 0){
            for (String key:param.keySet()){
                try {
                    stringBuilder.append(key+"=" + URLEncoder.encode(param.get(key), "utf-8")+"&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            strParam = stringBuilder.substring(0,stringBuilder.length()-1);
        }

        if(!"".equals(strParam)){
            url = url + "?" + strParam;
        }
        GetMethod method = new GetMethod(url);
        // 使用系统提供的默认的恢复策略
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        String result = null;
        try {
            // 执行getMethod
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                result = StreamUtils.copyToString(method.getResponseBodyAsStream(), Charset.forName("utf-8"));
            }
        } catch (IOException e) {
            logger.error("执行HTTP Get请求" + url + "时,发生异常!", e);
        } finally {
            method.releaseConnection();
        }
        return result;
    }


    /**
     * post请求,参数为json字符串
     * @param url 请求地址
     * @param jsonString json字符串
     * @return 响应
     */
    public static String doPost(String url,String jsonString)
    {
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间:5000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        postMethod.addRequestHeader("Content-Type", "application/json");
        String result = null;
        try {
            //json格式的参数解析
            RequestEntity entity = new StringRequestEntity(jsonString, "application/json", "UTF-8");
            postMethod.setRequestEntity(entity);

            httpClient.executeMethod(postMethod);
            if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                result  = postMethod.getResponseBodyAsString();
            }
        } catch (IOException e) {
            logger.error("post error info:"+e.getMessage());
        }finally {
            postMethod.releaseConnection();
        }
        return result;
    }


    /**
     * 生成微信配置json串
     *
     * @param jsApiList 要使用的微信接口
     * @param url 使用接口页面的地址带参数
     */
    public static Map<String, Object> generateConfig(String[] jsApiList, String url) {
        Map<String, Object> map = new HashMap<String, Object>();
        long timestamp = System.currentTimeMillis();
        String nonceStr = generateNonceStr();
        String signature = SHA1("jsapi_ticket=" + getJsapiTicket() + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url);
        map.put("appId", WeChatConfigController.cacheWxMap.get("app_id"));
        map.put("timestamp", timestamp);
        map.put("nonceStr", nonceStr);
        map.put("signature", signature);
        map.put("jsApiList", jsApiList);
        return map;
    }

    /**
     * 生成随机字符串
     */
    private static String generateNonceStr() {
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(CHARS[r.nextInt(CHARS.length)]);
        }
        return sb.toString();
    }

    /**
     * SHA1加密
     *
     * @param source 要加密的字符串
     */
    private static String SHA1(String source) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        byte[] byteArray = source.getBytes(Charset.forName("utf-8"));
        byte[] bytes = md.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte b : bytes) {
            int val = ((int) b) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }




    /**
     * 验证签名
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[] { TOKEN, timestamp, nonce };
        Arrays.sort(arr);

        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        // 3.将sha1加密后的字符串可与signature对比,标识该请求来源于微信
        Boolean asd = tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
        return asd;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        return new String(tempArr);
    }

    /**
     * 设置cookie
     * @param response
     * @param key cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期 以秒为单位
     * @param path cookie传递路径
     * @param domain cookie域
     */
    public static void addCookie(HttpServletResponse response, String key, String value, int maxAge, String path, String domain){
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(path);
//        cookie.setDomain(domain);
        if (maxAge > 0){
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name){
        Cookie cookies[] = request.getCookies();
        if (cookies != null){
            for (int i = 0; i < cookies.length; i++){
                Cookie cookie = cookies[i];
                if (name.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 删除目录(文件夹)以及目录下的文件
     * @param   sPath 被删除目录的文件路径
     * @return  目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }


    public static void main(String[] args) {
//        Template tem = new Template();
//        tem.setTemplateId("pO8bhYqcgEO2A4U_uoAdZw4OStFgni58Oce4ZIr1ngI");
//        tem.setTopColor("#00DD00");
//        tem.setToUser("oEN-qw8AigPCCWdscpyRJ2zCnsto");
//        tem.setUrl("http://www.baidu.com");
//        List<TemplateParam> paras=new ArrayList<TemplateParam>();
//        paras.add(new TemplateParam("userName","林志玲","#FF3333"));
//        paras.add(new TemplateParam("roomName","多媒体教室","#0044BB"));
//        paras.add(new TemplateParam("dateTime","2020-08-10","#0044BB"));
//        paras.add(new TemplateParam("status","success","#0044BB"));
//        tem.setTemplateParamList(paras);
//        System.out.println(sendTemplateMsg(tem));
        String token = WeiXinUtils.getToken();
        String result = WeiXinUtils.doGet(WeiXinUtils.GET_MENU + token, new HashMap<String, String>());
        Map<String,Map> mapResult = (Map<String, Map>) JSON.parse(result);



        System.out.println(mapResult.get("selfmenu_info").get("button"));
        System.out.println(mapResult);
    }

}

用来保存token,和微信相关交互

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值