JAVA对接微信登录,有这一篇就够了
在调用这个api的时候需要一个HttpClient工具
private static final CloseableHttpClient httpclient = HttpClients.createDefault(); /** * 发送HttpGet请求 * @param url 请求地址 * * @return 返回字符串 */ public static String sendGet(String url, Map<String, String> headerList) throws Exception{ String result = null; CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(url); if(headerList != null){ Set<String> keySet = headerList.keySet(); for (String key :keySet) { httpGet.setHeader(key, headerList.get(key)); } } response = httpclient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity); } } finally { if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
此工具类需要两个依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.7</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> <scope>compile</scope> </dependency>
public void getAuth(Map<String,Object> params){ String url = ""; //此处是你的api params中会携带参数入jsCode,iv,rawData,userInfo等参数 try { String sendGet = sendGet(url, null); JSONObject jsonObject = JSONObject.parseObject(sendGet); Object openId = jsonObject.get("openId"); Object session_key = jsonObject.get("session_key"); } catch (Exception e) { e.printStackTrace(); } }
需要注意: 前端在调用wx.login和wx.getUserInfo的时候只调用后端的一个接口就可以了,前端获取到jsCode以及加密的数据包和IV等数据时,直接调用后端接口,由后端操作!
得到了session_key之后,我们就可以解密数据,我们需要一个解密的数据util,注: 使用这个util的时候注意导包的位置
此工具类需要的pom坐标
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.59</version> </dependency>
得到这个界面算法之后我们就可以解密数据了,login接口就可以是这样的了
说一下思路:
好了今天就到这里
下一篇:
JVM-运行时数据区:虚拟机栈