JAVA之微信根据code获取openId

本文介绍了一种使用Java通过微信API获取用户OpenId、昵称和头像的方法。通过解析HTTP请求返回的JSON数据,实现了从code到用户详细信息的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

public class myTest {
    @Test
    public void userInfoTest() {
        String appId = "";
        String secret = "";
        String code = "";
        String userInfo = getOpenIdByCode(appId, secret, code);
        System.out.println(userInfo);
    }

    /**
     * 微信根据code获取openId
     * HttpClientUtil请求工具类
     */
    private String getOpenIdByCode(String appId, String secret, String code) {
        String userInfo = "";
        //String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        String accessUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, secret, code);
        String accessTokenStr = HttpClientUtil.httpGet(accessUrl);
        JSONObject jsonObject = JSON.parseObject(accessTokenStr);
        if (jsonObject.get("errcode") != null)
            System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //根据openId和access_token获取用户头像和昵称
        String accessUrl2 = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId);
        String accessTokenStr2 = HttpClientUtil.httpGet(accessUrl2);
        JSONObject jsonObject2 = JSON.parseObject(accessTokenStr2);
        if (jsonObject2.get("errcode") != null)
            System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
        String nickname = jsonObject2.getString("nickname");
        String headimgurl = jsonObject2.getString("headimgurl");
        userInfo = "用户OpenId:" + openId + "用户昵称:" + nickname + "用户头像地址:" + headimgurl;
        return userInfo;
    }
}

JAVA请求工具类之HttpClientUtil

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值