JAVA 获取微信用户信息,看完这篇你必须得学会

public static String doGet(String url, Map<String, String> param) {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = “”;

CloseableHttpResponse response = null;

try {

// 创建uri

URIBuilder builder = new URIBuilder(url);

if (param != null) {

for (String key : param.keySet()) {

builder.addParameter(key, param.get(key));

}

}

URI uri = builder.build();

// 创建http GET请求

HttpGet httpGet = new HttpGet(uri);

// 执行请求

response = httpclient.execute(httpGet);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

resultString = EntityUtils.toString(response.getEntity(), “UTF-8”);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (response != null) {

response.close();

}

httpclient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

public static String doGet(String url) {

return doGet(url, null);

}

public static String doPost(String url, Map<String, String> param) {

// 创建Httpclient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

String resultString = “”;

try {

// 创建Http Post请求

HttpPost httpPost = new HttpPost(url);

// 创建参数列表

if (param != null) {

List paramList = new ArrayList<>();

for (String key : param.keySet()) {

paramList.add(new BasicNameValuePair(key, param.get(key)));

}

// 模拟表单

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);

httpPost.setEntity(entity);

}

// 执行http请求

response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), “utf-8”);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

public static String doPost(String url) {

return doPost(url, null);

}

public static String doPostJson(String url, String json) {

// 创建Httpclient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

String resultString = “”;

try {

// 创建Http Post请求

HttpPost httpPost = new HttpPost(url);

// 创建请求内容

StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

httpPost.setEntity(entity);

// 执行http请求

response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), “utf-8”);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

}

第二个工具类,跟微信碰头验证用的,SignUtil.java:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

/**

  • @Author : JCccc

  • @CreateTime : 2019/8/2

  • @Description :

**/

public class SignUtil {

private static String token = “weixinCoursexxxxx”;//填你自己的

public static boolean checkSignature(String signature, String timestamp, String nonce) {

String[] paramArr = new String[] { token, timestamp, nonce };

Arrays.sort(paramArr);

String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

String ciphertext = null;

try {

MessageDigest md = MessageDigest.getInstance(“SHA-1”);

byte[] digest = md.digest(content.toString().getBytes());

ciphertext = byteToStr(digest);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;

}

private static String byteToStr(byte[] byteArray) {

String strDigest = “”;

for (int i = 0; i < byteArray.length; i++) {

strDigest += byteToHexStr(byteArray[i]);

}

return strDigest;

}

private static String byteToHexStr(byte mByte) {

char[] Digit = { ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’ };

char[] tempArr = new char[2];

tempArr[0] = Digit[(mByte >>> 4) & 0X0F];

tempArr[1] = Digit[mByte & 0X0F];

String s = new String(tempArr);

return s;

}

}

然后最关键的东西,接口,WxLoginController.java:

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import com.springmvc.util.HttpClientUtil;

import com.springmvc.util.SignUtil;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.net.URLEncoder;

/**

  • @Author : JCccc

  • @CreateTime : 2019/8/2

  • @Description :

**/

@RestController

@RequestMapping(“/wxAuth”)

public class WxLoginController {

private static String APPID=“xxxxxx”;//填你自己的

private static String APPSECRET=“xxxxx”;//填你自己的

/**

  • 用于给微信验证token

  • @param request

  • @param response

  • @return

  • @throws IOException

*/

@RequestMapping(“/checkToken”)

public String checkToken(HttpServletRequest request,HttpServletResponse response) throws IOException {

// 微信加密签名

String signature = request.getParameter(“signature”);

// 时间戳

String timestamp = request.getParameter(“timestamp”);

// 随机数

String nonce = request.getParameter(“nonce”);

// 随机字符串

String echostr = request.getParameter(“echostr”);

if (SignUtil.checkSignature(signature, timestamp, nonce)) {

System.out.println(“校验token成功”);

return echostr;

}else{

System.out.println(“校验token不成功”);

return null;

}

}

/**

  • 用于获取出回调地址 (引导用户调用此接口,成功后自动调取回调地址然后取出用户信息)

  • @param response

  • @throws IOException

*/

@RequestMapping(“/login”)

public void wxLogin(HttpServletResponse response) throws IOException {

//请求获取code的回调地址

//用线上环境的域名或者用内网穿透,不能用ip

String callBack = “http://3xXXXXXXXi.natappfree.cc/wxAuth/callBack”;//域名填你自己的

//请求地址

String url = “https://open.weixin.qq.com/connect/oauth2/authorize” +

“?appid=” + APPID +

“&redirect_uri=” + URLEncoder.encode(callBack) +

“&response_type=code” +

“&scope=snsapi_userinfo” +

“&state=STATE#wechat_redirect”;

System.out.println(url);

//重定向

response.sendRedirect(url);

}

/**

  • 回调方法

  • @param request

  • @param response

  • @throws IOException

*/

// 回调方法

@RequestMapping(“/callBack”)

public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {

String code = request.getParameter(“code”);

//获取access_token

String url = “https://api.weixin.qq.com/sns/oauth2/access_token” +

“?appid=” + APPID +

“&secret=” + APPSECRET +

“&code=” + code +

“&grant_type=authorization_code”;

String result = HttpClientUtil.doGet(url);

System.out.println(“请求获取access_token:” + result);

//返回结果的json对象

JSONObject resultObject = JSON.parseObject(result);

//请求获取userInfo

String infoUrl = “https://api.weixin.qq.com/sns/userinfo” +

“?access_token=” + resultObject.getString(“access_token”) +

“&openid=” + resultObject.getString(“openid”) +

“&lang=zh_CN”;

String resultInfo = HttpClientUtil.doGet(infoUrl);

//此时已获取到userInfo,再根据业务进行处理

System.out.println(“请求获取userInfo:” + resultInfo);

return “hello!”;

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

最后

image.png

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
g-WR2A6DDX-1713388609217)]

[外链图片转存中…(img-S6ySbck7-1713388609218)]

[外链图片转存中…(img-XuMFyMcT-1713388609218)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

最后

[外链图片转存中…(img-QYxP4h0t-1713388609219)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值