微信公众号开发--获取access_token和Ticket

获取access_token官方文档链接
这里来是做的定时任务,服务器启动的时候和每一百分钟获取一次,access_token和Ticket,并存到数据库,后面代码中用到直接在数据库中取值就可以了,access_token是唯一标识,Ticket在后面的微信开发中用的到,这里全部直接获取,有效期都是两小时

主逻辑代码

import system.domain.AccesstokenDO;
import system.service.AccesstokenService;
import util.AuthUtil;
import util.HttpRequest;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AccessTokenController {
    @Autowired
    AccesstokenService accesstokenService;
    //刷新access_token 100分钟刷新一次,服务器启动的时候刷新一次(access_token有效期是120分钟,我设置的是每100分钟刷新一次)
    @Scheduled(initialDelay = 1000, fixedDelay = 100*60*1000)
    public void getToken() {
        System.out.println("定时任务启动了");
        // 微信管理后台获取
        String wxspAppid = AuthUtil.APP_ID;
        // 微信管理后台获取
        String wxspSecret = AuthUtil.APP_SECRET;
        //这里直接写死就可以,不用改,用法可以去看api
        String grant_type="client_credential";
        //封装请求数据
        String params = "grant_type=" + grant_type + "&secret=" + wxspSecret + "&appid="+ wxspAppid;
        //发送GET请求
        String sendGet = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        // 解析相应内容(转换成json对象)
        JSONObject json = new JSONObject(sendGet);
        //拿到accesstoken
        String accesstoken = (String) json.get("access_token");
        // 拿到accesstoken的有效期
        String  expiresin = json.get("expires_in").toString();
        Long integer = Long.valueOf(expiresin);
        Long i = integer * 1000;
        //获取当前时间戳-->开始时间-->毫秒
        Long begintime = System.currentTimeMillis();
        //获取当前时间戳-->结束时间-->毫秒
        Long endtime = begintime+i;
        //  ticket的有效期为7200秒
        String ticket = null;
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ accesstoken +"&type=jsapi";//这个url链接和参数不能变
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            net.sf.json.JSONObject demoJson = net.sf.json.JSONObject.fromObject(message);
            System.out.println("JSON字符串:"+demoJson);
            ticket = demoJson.getString("ticket");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取Ticket
        String jsapi_ticket = ticket;
        //创建查询条件
        Map map= new HashMap();
        map.put("appid",wxspAppid);
        List<AccesstokenDO> list = accesstokenService.list(map);
        // 把获取的数据放到数据库中
        AccesstokenDO accesstokenDO = new AccesstokenDO();
        accesstokenDO.setAppid(wxspAppid);
        accesstokenDO.setBegintime(begintime.toString());
        accesstokenDO.setEndtime(endtime.toString());
        accesstokenDO.setAccesstoken(accesstoken);
        accesstokenDO.setTicket(jsapi_ticket);
        if (list.size()==0){
            accesstokenService.save(accesstokenDO);
        }else{
            AccesstokenDO accesstokenDO1 = list.get(0);
            Integer id = accesstokenDO1.getId();
            accesstokenDO.setId(id);
            accesstokenService.update(accesstokenDO);
        }
        System.out.println("定时任务结束了");
    }
}

实体类

public class AccesstokenDO{
	private Integer id;
	private String accesstoken;
	private String begintime;
	private String endtime;
	private String appid;
	private String ticket;

	public String getTicket() {
		return ticket;
	}
	public void setTicket(String ticket) {
		this.ticket = ticket;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getId() {
		return id;
	}
	public void setAccesstoken(String accesstoken) {
		this.accesstoken = accesstoken;
	}
	public String getAccesstoken() {
		return accesstoken;
	}
	public void setBegintime(String begintime) {
		this.begintime = begintime;
	}
	public String getBegintime() {
		return begintime;
	}
	public void setEndtime(String endtime) {
		this.endtime = endtime;
	}
	public String getEndtime() {
		return endtime;
	}
	public void setAppid(String appid) {
		this.appid = appid;
	}
	public String getAppid() {
		return appid;
	}
}

工具类

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * 工具类  用来根据接口地址进行网络请求
 */
public class AuthUtil {
    public static final String APP_ID =     //填写自己的APPID
    public static final String APP_SECRET =  //填写自己的APPSECRET
    public static JSONObject doGetJson(String url) throws Exception{
        JSONObject jsonObject=null;
        //初始化httpClient
        DefaultHttpClient client=new DefaultHttpClient();
        //用Get方式进行提交
        HttpGet httpGet=new HttpGet(url);
        //发送请求
        HttpResponse response= client.execute(httpGet);
        //获取数据
        HttpEntity entity=response.getEntity();
        //格式转换
        if (entity!=null) {
            String result= EntityUtils.toString(entity,"UTF-8");
            jsonObject= JSONObject.fromObject(result);
        }
        //释放链接
        httpGet.releaseConnection();
        return jsonObject;
    }
}

工具类

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 单参数数据访问
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String doPost(String postUrl, JSONObject obj) {
        String lines = "";
        StringBuffer sb = new StringBuffer("");
        try {
            // 创建连接
            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            // out.writeChars(obj.toString());
            // out.write(obj.toString().getBytes("UTF-8"));
            out.write(obj.toString().getBytes());
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

还有就是service层在和sql语句就不粘贴了,每一个人用的东西不一样,喜欢的可以收藏,关注,评论,不喜欢的就当没看见

你可能感兴趣的:(微信公众号开发)