多瓣郁金香 發表於 2020-8-21 18:23:00

Spring Boot 微信公众号开发(三) access_token

<h1 id="一token">一、Token</h1>
<p>access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。</p>
<p><strong>token的获取参考文档</strong></p>
<p>获取的流程我们完全可以参考微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html</p>
<p><strong>流程分析:</strong></p>
<ul>
<li>从公众平台获取账号的AppID和AppSecret;</li>
<li>token获取并解析存储执行体;</li>
<li>采用定时任务每隔两小时执行一次token获取执行体;</li>
</ul>
<h1 id="二实现">二、实现:</h1>
<h2 id="1参数获取">1、参数获取:</h2>
<p><strong>(1)在微信公众号官网获取参数,并配置进yml文件中</strong><br>
<img src="https://img2020.cnblogs.com/blog/1694537/202008/1694537-20200821182223851-594876466.png" alt="" loading="lazy"></p>
<p><strong>(2)yml配置:</strong><br>
<img src="https://img2020.cnblogs.com/blog/1694537/202008/1694537-20200821182230972-393331284.png" alt="" loading="lazy"></p>
<h2 id="2-http工具类">2、 http工具类:</h2>
<p>需要导入httpclient</p>
<pre><code class="language-xml">                &lt;dependency&gt;
            &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;
            &lt;artifactId&gt;httpclient&lt;/artifactId&gt;
            &lt;version&gt;4.5.2&lt;/version&gt;
      &lt;/dependency&gt;
</code></pre>
<p><strong>代码如下</strong></p>
<pre><code class="language-java">
/**
* @author yh
* @date 2020/8/21 16:11
* @description:
*/
public class HttpUtils {

    /**
   * @author: yh
   * @description: http get请求共用方法
   * @date: 2020/8/21
   * @param reqUrl
   * @param params
   * @return java.lang.String
   **/
    @SuppressWarnings("resource")
    public static String sendGet(String reqUrl, Map&lt;String, String&gt; params)
            throws Exception {
      InputStream inputStream = null;
      HttpGet request = new HttpGet();
      try {
            String url = buildUrl(reqUrl, params);
            HttpClient client = new DefaultHttpClient();

            request.setHeader("Accept-Encoding", "gzip");
            request.setURI(new URI(url));

            HttpResponse response = client.execute(request);

            inputStream = response.getEntity().getContent();
            String result = getJsonStringFromGZIP(inputStream);
            return result;
      } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            request.releaseConnection();
      }

    }

    /**
   * @author: yh
   * @description: http post请求共用方法
   * @date: 2020/8/21
   * @param reqUrl
   * @param params
   * @return java.lang.String
   **/
    @SuppressWarnings("resource")
    public static String sendPost(String reqUrl, Map&lt;String, String&gt; params)
            throws Exception {
      try {
            Set&lt;String&gt; set = params.keySet();
            List&lt;NameValuePair&gt; list = new ArrayList&lt;NameValuePair&gt;();
            for (String key : set) {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            if (list.size() &gt; 0) {
                try {
                  HttpClient client = new DefaultHttpClient();
                  HttpPost request = new HttpPost(reqUrl);

                  request.setHeader("Accept-Encoding", "gzip");
                  request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

                  HttpResponse response = client.execute(request);

                  InputStream inputStream = response.getEntity().getContent();
                  try {
                        String result = getJsonStringFromGZIP(inputStream);

                        return result;
                  } finally {
                        inputStream.close();
                  }
                } catch (Exception ex) {
                  ex.printStackTrace();
                  throw new Exception("网络连接失败,请连接网络后再试");
                }
            } else {
                throw new Exception("参数不全,请稍后重试");
            }
      } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("发送未知异常");
      }
    }

    /**
   * @author: yh
   * @description: http post请求json数据
   * @date: 2020/8/21
   * @param urls
   * @param params
   * @return java.lang.String
   **/
    public static String sendPostBuffer(String urls, String params)
            throws ClientProtocolException, IOException {
      HttpPost request = new HttpPost(urls);

      StringEntity se = new StringEntity(params, HTTP.UTF_8);
      request.setEntity(se);
      // 发送请求
      @SuppressWarnings("resource")
      HttpResponse httpResponse = new DefaultHttpClient().execute(request);
      // 得到应答的字符串,这也是一个 JSON 格式保存的数据
      String retSrc = EntityUtils.toString(httpResponse.getEntity());
      request.releaseConnection();
      return retSrc;

    }

    /**
   * @author: yh
   * @description:http请求发送xml内容
   * @date: 2020/8/21
   * @param urlStr
   * @param xmlInfo
   * @return java.lang.String
   **/
    public static String sendXmlPost(String urlStr, String xmlInfo) {
      // xmlInfo xml具体字符串

      try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = new OutputStreamWriter(
                  con.getOutputStream());
            out.write(new String(xmlInfo.getBytes("utf-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                  con.getInputStream()));
            String lines = "";
            for (String line = br.readLine(); line != null; line = br
                  .readLine()) {
                lines = lines + line;
            }
            return lines; // 返回请求结果
      } catch (MalformedURLException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
      return "fail";
    }
    /**
   * @author: yh
   * @description:
   * @date: 2020/8/21
   * @param is
   * @return java.lang.String
   **/
    private static String getJsonStringFromGZIP(InputStream is) {
      String jsonString = null;
      try {
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte;
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            // Gzip 流 的前两个字节是 0x1f8b
            if (result != -1 &amp;&amp; headerData == 0x1f8b) {
                // LogUtil.i("HttpTask", " use GZIPInputStream");
                is = new GZIPInputStream(bis);
            } else {
                // LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char;
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) &gt; 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
      } catch (Exception e) {
            e.printStackTrace();
      }

      return jsonString;
    }

    private static int getShort(byte[] data) {
      return (data &lt;&lt; 8) | data &amp; 0xFF;
    }

    /**
   * @author: yh
   * @description: 构建get方式的url
   * @date: 2020/8/21
   * @param reqUrl 基础的url地址
   * @param params 查询参数
   * @return java.lang.String
   **/
    public static String buildUrl(String reqUrl, Map&lt;String, String&gt; params) {
      StringBuilder query = new StringBuilder();
      Set&lt;String&gt; set = params.keySet();
      for (String key : set) {
            query.append(String.format("%s=%s&amp;", key, params.get(key)));
      }
      return reqUrl + "?" + query.toString();
    }
}

</code></pre>
<h2 id="3配置类读取参数">3、配置类读取参数</h2>
<pre><code class="language-java">

/**
* @author yh
* @date 2020/8/21 17:24
* @description:
*/
@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class WeChatConfiguration {

    private String appid;

    private String AppSecret;

    private String tokenUrl;

}
</code></pre>
<h2 id="4设置定时任务获取token">4、设置定时任务获取token</h2>
<pre><code class="language-java">

/**
* @author yh
* @date 2020/8/21 16:39
* @description: 定时任务
*/
@Component
@Slf4j
public class WeChatTask {

    @Resource
    private TaskService taskService;


    @PostMapping("/getToken")
    @Scheduled(fixedDelay=2*60*60*1000)
    public void getToken() throws Exception {
      log.info("定时任务:重新获取token");
      taskService.getToken();
    }

}

</code></pre>
<pre><code class="language-java">
/**
* @author yh
* @date 2020/8/21 16:43
* @description:
*/
@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private WeChatConfiguration weChatConfiguration;
    /**
   * @author: yh
   * @description: 获取微信token
   * @date: 2020/8/21
   * @param
   * @return void
   **/
    @Override
    public void getToken() throws Exception {

      Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();

      params.put("grant_type", "client_credential");
      params.put("appid", weChatConfiguration.getAppid());
      params.put("secret", weChatConfiguration.getAppSecret());

      String json = HttpUtils.sendGet(weChatConfiguration.getTokenUrl(), params);
      String access_token = JSONObject.parseObject(json).getString("access_token");

      System.out.println(LocalDateTime.now() +"token为=============================="+access_token);
    }
}

</code></pre><br><br>
来源:https://www.cnblogs.com/yyanghang/p/13542491.html
頁: [1]
查看完整版本: Spring Boot 微信公众号开发(三) access_token