亲宝软件园·资讯

展开

java获取微信accessToken的方法

人气:0

package com.fengdi.lianmeng.task;

import com.fengdi.lianmeng.common.CacheHelper;
import com.fengdi.lianmeng.util.http.HttpRequest;
import com.fengdi.lianmeng.util.tencent.CloudSignHelper;
import com.fengdi.lianmeng.util.tencent.Interface;
import net.sf.json.JSONObject;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 定时获取微信accessToken
 */

public class GetWeiXinAccessTokenTask {

 private static Logger logger = LoggerFactory.getLogger(GetWeiXinAccessTokenTask.class);

 /**
 * 每90分钟,获取一次微信accessToken
 */
 public void getWeiXinAccessToken (JobExecutionContext context){
 try{
  logger.info("获取微信定时AccessToken任务启动了");

  //封装请求数据
  String params = "grant_type=client_credential" + 
  "&secret=" + CloudSignHelper.wxspSecret + //小程序的 app_secret (在微信小程序管理后台获取)
  "&appid="+ CloudSignHelper.appid;//小程序唯一标识appid (在微信小程序管理后台获取)
  //发送GET请求
  String result = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
  // 解析相应内容(转换成json对象)
  JSONObject jsonObject = JSONObject.fromObject(result);
  String accessToken = (String) jsonObject.get("access_token");

  CacheHelper.put("wxAccessToken", accessToken);//将accessToken放入缓存,用的时候取就行
  logger.info("获取微信定时AccessToken任务结束了");
 }catch(Exception ex){
  logger.error("获取微信定时AccessToken任务失败." , ex);
 }
 }
}

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();
      // 遍历所有的响应头字段
      for (String key : map.keySet()) {
        System.out.println(key + "--->" + map.get(key));
      }
      // 定义 BufferedReader输入流来读取URL的响应
      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      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;
  }
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论