微信公众号开发工具类

package jvm;

import sun.net.www.http.HttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
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.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by HuiSheng1 on 2016/12/15.
 */
public class WeiXinUtil {
    public static final String APPID = "APPID";
    public static final String SECRET = "SECRET";
    public static final int TIME_WAIT = 10 * 1000;
    public static long expires_in = 7200;
    public static long lastSystemCurrentTimeMillis = System.currentTimeMillis();
    public static String access_token;// 接口调用

    public static long lastSystemCurrentTimeMillisOfPage = System.currentTimeMillis();
    public static long expires_in_page = 7200;
    public static String access_token_page; // 网页授权用

    public static long lastSystemCurrentTimeMillisOfPageRefresh = System.currentTimeMillis();
    public static long expires_in_refresh = 30 * 24 * 60 * 60; // 30天过期,单位秒
    public static String refresh_token;// 网页授权刷新用

    public static String getAccessToken() {

        long timeLeft = System.currentTimeMillis() - lastSystemCurrentTimeMillis
        if (access_token == null || (timeLeft > expires_in * 1000 - TIME_WAIT && timeLeft < expires_in * 1000)) {
            String at = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
            String result = getDataFromUrl(at);
            JsonSlurper json = new JsonSlurper().parseText(result);
            access_token = json.getAt("access_token").toString();
            expires_in = Long.parseLong(json.getAt("expires_in").toString());
            lastSystemCurrentTimeMillis = System.currentTimeMillis();
        }

        return access_token;
    }

    public static String getAccessTokenOfPage(String code) {
        // 通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code"
        String result = getDataFromUrl(url);
        json = new JsonSlurper().parseText(result);
        access_token_page = json.getAt("access_token").toString();
        expires_in_page = Long.parseLong(json.getAt("expires_in").toString());
        refresh_token = json.getAt("refresh_token").toString();
        lastSystemCurrentTimeMillisOfPage = System.currentTimeMillis();
        lastSystemCurrentTimeMillisOfPageRefresh = System.currentTimeMillis();
//
        return refresh_token;
    }

    /**
     * 创建菜单
     */
    public static void createMenu() {
        String access_token = getAccessToken();
        //创建新菜单
        String menu = "";//要创建的微信自定义菜单
        String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        menu_create_url = menu_create_url.replace("ACCESS_TOKEN", access_token);
        String result2 = getDataFromUrl(menu_create_url, "POST", menu);
        System.out.print(result2);

    }

    //执行访问微信接口
    public static String getDataFromUrl(String url, String methods, String menu) {
        String result = "";
        try {
            HttpClient client = new HttpClient();
            if ("GET".equals(methods)) {
                HttpMethod method = new GetMethod(url);
                client.executeMethod(method);
                result = method.getResponseBodyAsString();
                method.releaseConnection();
            } else {
                PostMethod method = new PostMethod(url);
                method.setRequestHeader("Content-Type", "text/xml;charset=utf8");
                RequestEntity requestEntity = new StringRequestEntity(menu, "text/xml", "utf8");
                method.setRequestEntity(requestEntity);
                client.executeMethod(method);
                InputStream ins = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sbf.append(line);
                }

                br.close();
                result = sbf.toString();
            }
        } catch (IOException e) {
        }
        return result;
    }

    public static String getWxAeecssToken(String code, String appid, String secret) {
        String openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        openid_url = openid_url.replaceAll("APPID", appid).replaceAll("SECRET", secret).replaceAll("CODE", code);
        String result = getDataFromUrl(openid_url, "GET", "");
//        System.out.println("openid result: "+result);
        JSONObject json = new JSONObject().fromObject(result);
        return json.get("access_token").toString();
    }

    //获取用户基本信息,暂时只获取是否关注公众号
    public static String getWxUserInfo(String access_token, String openid) {
        String userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        userInfo_url = userInfo_url.replaceAll("ACCESS_TOKEN", access_token).replaceAll("OPENID", openid);
        String result = getDataFromUrl(userInfo_url, "GET", "");
        JSONObject json = new JSONObject().fromObject(result);
        //获取其他基本信息的时候需要先判断是否关注,即subscribe是否为0,如果subscribe为0,则只能得到subscribe和openid,获取其他信息会报空指针
        return json.get("subscribe").toString();
    }

    public static void main(String[] args) {
        createMenu();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值