欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

[Java + WxPay] Java获取openId,

来源: javaer 分享于  点击 43317 次 点评:162

[Java + WxPay] Java获取openId,


微信小程序webview进行支付时, 需要获取openId, 原本在小程序上获取, 后来微信不允许, 现在在后台获取.

工具类:

/**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    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 e) {
                e.printStackTrace();
            }
        }
        return result;
    }

获取请求体

String res = sendGet("https://api.weixin.qq.com/sns/jscode2session",
                "appid=" + appId + "&secret=" + secretId + "&js_code=" + js_code + "&grant_type=authorization_code");

此处可用Gson等工具将res字符串转换为对象, 方便操作. 如:

Map resMap = new Gson().fromJson(res, Map.class);
String openId = resMap.get("openid").toString();

注意: 需要按需做异常处理. 只有请求成功时openid才可以获取到

相关文章

    暂无相关文章
相关栏目:

用户点评