微信小程序获取openId ---- JAVA

前端代码:
小程序登录时获取code

wx.login({
  success: res => {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //that.data.url 你的服务器地址
    wx.request({
      url: that.data.url + '/mini_Weixin_getOpenId.action',
      data:{"code":res.code},
      method:'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
          openId = res.data;
      }
    })
  }
})

后端代码:

controller类:

public String getOpenId(String code){
		String url = " https://api.weixin.qq.com/sns/jscode2session?appid="+小程序appid+"&secret="+小程序appsecret+"&js_code="+code+"&grant_type=authorization_code";
		String rst = doGet(url, "GBK");
		System.out.println("rst==="+rst);
		logger.info("rst==="+rst);
		try {
			String tmp = "\"openid\":\"";
			rst = rst.substring(rst.indexOf(tmp)+tmp.length());
			rst = rst.substring(0, rst.indexOf("\""));
		} catch (Exception e) {
			e.printStackTrace();
			rst = "";
		}		
		return rst;
}

util类

/**
 * http get 提交
 * @param url
 * @param charset
 * @return
 */
public static String doGet(String url, String charset) {
	try {
		URL httpURL = new URL(url);
		HttpURLConnection http = (HttpURLConnection) httpURL
				.openConnection();
		http.setRequestProperty("Content-type", "text/html");
		BufferedReader br = new BufferedReader(new InputStreamReader(http
				.getInputStream(), charset));
		StringBuilder sb = new StringBuilder();
		String temp = null;
		while ((temp = br.readLine()) != null) {
			sb.append(temp);
			sb.append("\n");
		}
		br.close();
		return sb.toString();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

完。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值