- 最近在写微信相关接口,我真的是。。。。哎
- 首先先写个url请求工具类
import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public static String sendGet(String url, String charset, int timeout) { String result = ""; try { URL u = new URL(url); try { URLConnection conn = u.openConnection(); conn.connect(); conn.setConnectTimeout(timeout); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line = ""; while ((line = in.readLine()) != null) { result = result + line; } in.close(); } catch (IOException e) { return result; } } catch (MalformedURLException e) { return result; } return result; }
- 获取token(因为token2小时会过期,我起了个定时任务,项目启动后2小时会自动获取token,并且加入缓存,需要放到服务器去测试,不然搞不了。。。应该是微信安全做了什么措施)
//地址 public static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=SECRET";
import net.sf.json.JSONObject; public static String getAccessToken(String appId, String secret) { String backData = sendGet(TOKEN_URL.replace("APP_ID", appId).replace("SECRET", secret), "utf-8", 10000); log.info("============》获取accessToken{}", JSON.toJSONString(backData)); String accessToken = (String) JSONObject.fromObject(backData).get("access_token"); return accessToken; }
-
maven配置
net.sf.json-lib json-lib-ext-spring 1.0.2
-
-
获取ticket
public static String getJSApiTicket(String acessToken) { //获取token String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acessToken + "&type=jsapi"; String backData = sendGet(urlStr, "utf-8", 10000); String ticket = (String) JSONObject.fromObject(backData).get("ticket"); return ticket; }
-
获取public_number_openId
//APP_ID和SECRET写成自己的即可public static final String PUBLIC_NUMBER_OPEN_ID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APP_ID&secret=SECRET&code=CODE&grant_type=authorization_code";public static Map
getPublicNumberOpenId(String code) { Map returnMap = new HashMap<>(); //获取token log.info("==========》获取unionID,code是:" + code); String backData = sendGet(PUBLIC_NUMBER_OPEN_ID_URL.replace("CODE", code), "utf-8", 10000); log.info("==========》获取openID:" + backData); String openId = (String) JSONObject.fromObject(backData).get("openid"); returnMap.put("openId", openId); return returnMap; } -
获取small_program_openId
//APP_ID和SECRET换成自己public static final String SMALL_PROGRAM_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APP_ID&secret=SECRET&js_code=CODE&grant_type=authorization_code";public static Map
getSmallProgramOpenId(String code) { Map returnMap = new HashMap<>(); //获取token log.info("==========》获取unionID,code是:" + code); String backData = sendGet(SMALL_PROGRAM_OPEN_ID_URL.replace("CODE", code), "utf-8", 10000); log.info("==========》获取openID:" + backData); String openId = (String) JSONObject.fromObject(backData).get("openid"); returnMap.put("openId", openId); return returnMap; } -
下篇会写一些关于自定义消息回复的功能