微信公众号开发后台通过code获取openId

    public static String weiXinLoginGetOpenId(String code) throws Exception {
        URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid=xxx&secret=xxx&js_code=" + code);
		URLConnection urlConnection =  url.openConnection();
        HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.setConnectTimeout(3000);
        // 设置请求头属性参数
        httpUrlConnection.setRequestProperty("charset", "UTF-8"); 
        httpUrlConnection.setRequestProperty("accept", "application/json");
        String response = "";// 响应内容
        String status = "";// 响应状态
        PrintWriter out = null;
        BufferedReader in = null;
        try{
        	httpUrlConnection.connect();
            // 定义BufferedReader输入流来读取URL的响应数据
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
            // 获得URL的响应状态码
            status = new Integer(httpUrlConnection.getResponseCode()).toString();
        }catch(Exception e) {
        	logger.error("发送Get请求获取微信的openId出现错误", e);
        }finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
            	logger.error("发送Get请求获取微信的openId出现错误", ex);
            }
        }
        PageData typeValueData = new Gson().fromJson(response, PageData.class);
        logger.info("响应状态:"+status);
        logger.info("响应内容:"+response);
		return typeValueData.getString("openid");
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值