一、認清auth.getAccessToken
這個接口不是wx.request()之類的在小程序端使用,它在服務器中編寫代碼使用,是一種請求規范。向微信服務器請求access_token時必須遵守的規范。即:(1)請求方式為GET (2)請求網址為https://api.weixin.qq.com/cgi-bin/token?(3)必須附帶三個參數:grant_type,appid,secret.滿足以上條件可以向服務器申請獲得access_token,因而需要掌握網絡請求相關的代碼知識。
二、代碼實現(JAVA為例)
(1)編寫HttpRequest工具類
package com.data.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { public 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(), "utf-8")); // 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; } }
(2調用工具類發起請求:
import com.data.service.HttpRequest; import net.sf.json.JSONObject; String APP_ID=request.getParameter("id"); String APPSECRET=request.getParameter("secret"); String grant_type="client_credential"; HttpRequest requestion=new HttpRequest(); String params = "grant_type=" + grant_type + "&secret=" + APPSECRET + "&appid="+ APP_ID; String sendGet = requestion.sendGet("https://api.weixin.qq.com/cgi-bin/token", params); JSONObject json = JSONObject.fromObject(sendGet); String accesstoken = (String) json.get("access_token"); //accesstoken即為申請得到的access_token(這個值兩小時就會失效 2022)
引用:https://blog.csdn.net/weixin_41716049/article/details/84066112
https://www.jianshu.com/p/70d5f80c16b8;
以上看法為個人所見,歡迎指正。