废话少说,直接上代码!!!!

首先封装一个方法用于接收请求微信的参数。

使用到HttpURLConnection 用于发送远程接口请求。(HttpClient也可以)

/**
     * <pre>
     * 向远程接口发起请求,返回字节流类型结果
     * @param url 接口地址
     * @return InputStream 返回结果
     * </pre>
     */
    public static InputStream httpRequestToStream(String url){
        InputStream is = null;
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            //请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Content-Type为“”空)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置连接超时时间
            conn.setConnectTimeout(50000);
            //设置读取返回内容超时时间
            conn.setReadTimeout(50000);
            //设置从HttpURLConnection对象读入,默认为true
            conn.setDoInput(true);
            //从HttpURLConnection对象中读取响应的消息
            //执行该语句时才正式发起请求
            is = conn.getInputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

接下来只需要传你的appid和secret就可以调用!!非常简单

@GetMapping("getByToken")
    public static String httpRequestToString(String appid, String secret){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;

        String result = null;
        try {
            InputStream is = httpRequestToStream(url);
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

测试结果:

 完美解决!!

可能会出现状态码40164的情况是因为你的微信公众平台没有开启白名单,添加一个白名单即可!!

 创作不易,免费开源,希望大家点个小爱心!!!

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐