首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为何通过code获取openid失败?

为何通过code获取openid失败?

提问于 2022-05-24 17:20:28
回答 2关注 0查看 340

目的:通过code获取openid

问题描述:通过POST请求,微信小程序将code传递给后台,后台返回openid。本地测试,代码部署阿里云服务器(以docker容器运行)都可正常实现,但是将后台代码发布到微信云托管,始终无法获取到openid

代码如下:

代码语言:js
复制
	/**
	 * 通过Code获取微信OpenID
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 */
	private String getOpenID(String code) throws Exception {
		// System.out.println("code" + code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=" + AppID;//自己的appid
        url += "&secret=" + Secret;//自己的appSecret
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        url += "&connect_redirect=1";
        String res = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);    //GET方式
        CloseableHttpResponse response = null;
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
        httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
        response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        // System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            res = EntityUtils.toString(responseEntity);
            // System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            // System.out.println("响应内容为:" + res);
        }
        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
        JSONObject jo = JSON.parseObject(res);
        String openid = jo.getString("openid");
        // System.out.println("openid" + openid);
		return openid;
	}
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档