JAVA 使用Hutool的HttpRequest加FileUtil工具类 把获取的二进制作图片内容进行保存

在使用小程序生成二维API接口时,通过HttpRequest请求获取到的Buffer为二进制内容,需要返回值必须为Byte类型,返回String类型就会变成乱码

下面直接上我的获取二维码方法,获取asscess_token略过:

    /**
     * 生成带参数的小程序二维码
     */
    public String getCode(String orgCode) throws RemoteException{
        //获取token
        String accessToken = this.getAccessToken();
        //发送消息请求URL
        String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+accessToken;
        JSONObject requestData = new JSONObject();
        requestData.put("path","pages/make/settlement?orgCode="+orgCode);
        requestData.put("width",380);

        //这里要特别注意,调用二维码接口返回的是二进制,所以返回值必须为Byte类型,返回String类型就会变成乱码,所以不能使用body()必需要使用bodyBytes()
        byte[] qrCode = HttpRequest.post(url)
                .body(requestData.toString())
                .execute().bodyBytes();
        //这里就直接把二进制保存为文件就可以了
        //这里是自定义保存的文件路径
        String filePath = "../classes/data/uploads/code_"+orgCode+".jpg";
        File file = FileUtil.writeBytes(qrCode, filePath);
        return filePath;
    }

  

 

posted @ 2023-03-23 17:42  智昕  阅读(511)  评论(0编辑  收藏  举报