100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java根据微信小程序code获取用户openId

java根据微信小程序code获取用户openId

时间:2022-01-05 23:02:44

相关推荐

java根据微信小程序code获取用户openId

java根据小程序code获取用户openId

java根据小程序code获取用户openId上面用到一个工具方法

java根据小程序code获取用户openId

String result = HttpRequest.sendGet("https://api./sns/jscode2session", "appid=" + FgStaticParam.AppId + //小程序APPID"&secret="+ CloudSignHelper.wxspSecret + //小程序秘钥"&js_code="+ registerReq.getCode() + //前端传来的code"&grant_type=authorization_code");JSONObject jsonObject = JSONObject.parseObject(result);if (jsonObject.containsKey("errcode")) {throw new FdServiceException(ErrorCode.QUERY_EXCEPTION, "code无效");}String openId = jsonObject.get("openid").toString();if (StringUtils.isNullOrEmpty(openId)) {throw new FdServiceException(ErrorCode.QUERY_EXCEPTION, "openid为空");}

上面用到一个工具方法

public static 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()));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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。