政务微信下载文件--以政务微信消息形式推送呈现

近日接了个需求,要求下载人员名单,心想很简单的个功能,于是就三下五除二的完成了后端代码编写,然后把请求地址和请求参数发给了前端,结果前端反馈政务微信不支持下载文件,如下图所示:

什么情况???

于是咨询了大佬,给了两个方法,1.用H5新打开页面去下载,2、将下载文件推送到政务微信的消息中;于是就按第二种方式场所了;闲言少叙上代码:

这是前端直接调用的方法,此时前端无需以下载的方式调用,按正常接口调用即可

截图加源码

@ApiOperation(notes ="下载会议人员", value = "下载会议人员")
    @RequestMapping(value = "/excel_user", method = {RequestMethod.POST,RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "meetId", value = "meetId",required = true, dataType = "String", paramType = "query")
    })
    @ResponseBody
    public void excelUser(@RequestParam(value = "meetId") String meetId){
        try {
            String streamNo=DateUtil.getCurrentCompactTime();
            Map<String, Object> params = new HashMap();
            params.put("meetId", meetId);
            List<Map<String, Object>> dataList= hyMeetinginfoService.excelExportReportList(meetId);
            String sheetName = (String) dataList.get(0).get("meetName");
            String userId = hyMeetinginfoService.cxhyyh(meetId);
            //将下载文件上传临时素材文件获得mediaId
            String mediaId= WxSend.uploadPic("http://hy.ydjw.jcy.gov.cn:8080/prod-api/api/meeting/dow_user?meetId="+meetId,sheetName);//这里的URL就是下面下载文件的请求地址及参数
            if (StringUtils.isNotBlank(mediaId) && StringUtils.isNotBlank(userId)){
                Map<String, Object> contentText = new HashMap<>(1);
                contentText.put("media_id",mediaId);
                WxSend.sendFile(userId,contentText);//将文件发送消息
            }
            log.info(streamNo+"|会议名单文件发送至通知消息" +  "|meetId="+meetId);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

/********************************优美的分割线***********************************/

这是正常的下载文件代码

截图加源码

@ApiOperation(notes ="导出会议人员", value = "导出会议人员")
@RequestMapping(value = "/dow_user", method = {RequestMethod.POST,RequestMethod.GET})
@ApiImplicitParams({
        @ApiImplicitParam(name = "meetId", value = "meetId",required = true, dataType = "String", paramType = "query")
})
@ResponseBody
public void dowUser(@RequestParam(value = "meetId") String meetId,HttpServletRequest request,
                      HttpServletResponse response){
    try {
        String streamNo=DateUtil.getCurrentCompactTime();
        // 构造导出数据
        List<Map<String, Object>> dataList= hyMeetinginfoService.excelExportReportList(meetId);

        String sheetName = (String) dataList.get(0).get("meetName");
        String[] head0 = new String[] {"序号", "姓名","部门", "职务", "备注","报名时间"};//在excel中的第3行每列的参数
        String[] head1 = new String[] { "", "","",  "", "" };//在excel中的第4行每列(合并列)的参数
        //对应excel中的行和列,下表从0开始{"开始行,结束行,开始列,结束列"}
        String[] headnum0 = new String[] { "1,2,0,0","1,2,1,1","1,2,2,2","1,2,3,3","1,2,4,4","1,2,5,5"};//对应excel中的行和列,下表从0开始{"开始行,结束行,开始列,结束列"}
        String[] headnum1 = new String[] { "2,2,0,0","2,2,1,1", "2,2,2,2", "2,2,3,3","2,2,4,4"  };
        String[] colName = new String[] { "xh", "userName","bm", "zw", "bz", "bmsj"};//需要显示在excel中的参数对应的值,因为是用map存的,放的都是对应的key
        int colTable=6;//设置列数
        reportMergeXls(request, response, dataList, sheetName, head0,
                headnum0, head1, headnum1, colName,colTable); //utils类需要用到的参数
        log.info(streamNo+"|下载会议名单文件结束" + "|meetId="+meetId);
    } catch (Exception e) {
        log.error(e.getMessage(),e);
    }
}

/********************************优美的分割线***********************************/

这是下载的service

public List<Map<String,Object>> excelExportReportList(String meetId) {
    List<Map<String, Object>> result = new ArrayList<>();
    List<Map<String, Object>> userInfoList = hyMeetinginfoMapper.selectMeetUser(meetId);
    if (userInfoList != null && userInfoList.size() > 0) {
        int i=1;
        for (Map<String, Object> user:userInfoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("meetName", user.get("meetName"));
            map.put("xh", i++);
            map.put("userName", user.get("userName"));
            map.put("bm", user.get("bm"));
            map.put("zw", user.get("zw"));
            map.put("bz", user.get("bz"));
            map.put("bmsj", user.get("bmsj"));
            result.add(map);
        }
    }
    return result;
}

/********************************优美的分割线***********************************/

截图加源码

源码
//上传下载的文件至临时素材文件获得mediaId
    public static String uploadPic(String filePath,String sheetName) throws Exception{
        String accessToken = getAccessToken();
        //返回结果
        String result=null;
        URL url2 = new URL(filePath);
        URLConnection con = url2.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        String urlString="http://ydjw.jcy.gov.cn:90/cgi-bin/media/upload?access_token="+accessToken+"&type=file";
        URL url=new URL(urlString);
        HttpURLConnection conn=(HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");//以POST方式提交表单
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);//POST方式不能使用缓存
        //设置请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");;
        conn.setRequestProperty("Charset", "UTF-8");
        //设置边界
        String BOUNDARY="----------"+System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        //请求正文信息
        //第一部分
        StringBuilder sb=new StringBuilder();
        sb.append("--");//必须多两条道
        sb.append(BOUNDARY);
        sb.append("\r\n");
//        sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + filePath.substring(filePath.lastIndexOf("/")+1)+"\"\r\n");
        //必须注意文件格式
        sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" +sheetName+"."+"xls"+"\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        System.out.println("sb:"+sb);

        //获得输出流
        OutputStream out=new DataOutputStream(conn.getOutputStream());
        //输出表头
        out.write(sb.toString().getBytes("UTF-8"));
        //文件正文部分
        //把文件以流的方式 推送道URL中
        DataInputStream din=new DataInputStream(is);
        int bytes=0;
        byte[] buffer=new byte[1024];
        while((bytes=din.read(buffer))!=-1){
            out.write(buffer,0,bytes);
        }
        din.close();
        //结尾部分
        byte[] foot=("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
        out.write(foot);
        out.flush();
        out.close();
        if(HttpsURLConnection.HTTP_OK==conn.getResponseCode()){

            StringBuffer strbuffer=null;
            BufferedReader reader=null;
            try {
                strbuffer=new StringBuffer();
                reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lineString=null;
                while((lineString=reader.readLine())!=null){
                    strbuffer.append(lineString);

                }
                if(result==null){
                    result=strbuffer.toString();
                    System.out.println("result:"+result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    result = jsonObject.get("media_id").toString();
                    System.out.println("media_id:"+jsonObject.get("media_id"));
                }
            } catch (IOException e) {
                System.out.println("发送POST请求出现异常!"+e);
                e.printStackTrace();
            }finally{
                if(reader!=null){
                    reader.close();
                }
            }

        }
        return result;
    }

/********************************优美的分割线***********************************/

截图加源码

//文件发送给消息的形式
public static String  sendFile(String touser ,Map<String, Object> content) {
    String errmsg = null;
    String accessToken = getAccessToken();
    Gson gson = new Gson();
    Map<String, Object> map = new HashMap<>(5);
    map.put("touser", touser);
    map.put("msgtype", "file");//text
    map.put("agentid", "111111");
    content.put("url","URL");
    map.put("file", content);
    String s = gson.toJson(map);
    String url = "http://ydjw.jcy.gov.cn:90/cgi-bin/message/send?access_token=" + accessToken;
    String data = HttpUtil.post(url, s);
    if (data != null) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        errmsg = jsonObject.getString("errmsg");
    }
    return errmsg;
}

/********************************优美的分割线***********************************/

以上做完就可以达到预期要求了

### 使用Python开发政务微信接口 #### 准备环境 为了能够顺利地使用Python与政务微信进行集成或开发,首先需要准备相应的开发环境。这包括安装必要的依赖库以及配置开发工具。 对于依赖库而言,可以利用`requests`来处理HTTP请求,这是与外部API交互的基础[^3]。可以通过如下命令安装该库: ```bash pip install requests ``` 另外,在某些情况下可能还需要其他辅助库,比如用于解析JSON数据的库等。如果涉及到定时任务,则可考虑引入APScheduler来进行调度[^2]。 #### 获取Access Token 在调用微信提供的各类服务之前,通常都需要先获取access token。这是一个临时凭证,用来验证身份并获得访问权限。具体来说,通过向指定URL发起GET请求,并传递参数如AppID和AppSecret,便能收到包含有效token在内的响应体。 以下是简单的代码片段展示如何实现这一点: ```python import requests def get_access_token(app_id, app_secret): url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}" response = requests.get(url).json() if 'access_token' not in response: raise Exception(f"Failed to fetch access token: {response}") return response['access_token'] ``` #### 构建消息推送机制 当已经成功获得了有效的access token之后,就可以着手构建实际的消息推送逻辑了。这里以发送模板消息为例介绍基本流程:首先是准备好要发送的数据结构;接着设置好目标用户的OpenID以及其他必要字段;最后再把组装好的payload作为POST请求的内容提交给对应的API端点。 需要注意的是,不同类型的模板消息有不同的格式要求,因此务必参照官方文档仔细核对每一项输入是否正确。 ```python from datetime import datetime import json def send_template_message(access_token, open_id, template_id, data_dict): url = "https://api.weixin.qq.com/cgi-bin/message/template/send" payload = { "touser": open_id, "template_id": template_id, "data": data_dict, "url": "", # 可选链接地址 "miniprogram": {} # 小程序跳转路径(如果有) } headers = {'Content-Type': 'application/json'} params = {"access_token": access_token} response = requests.post( url=url, headers=headers, params=params, data=json.dumps(payload), ).json() if response["errcode"] != 0: raise Exception(f"Error sending message: {response}") print("Message sent successfully.") ``` 以上就是关于怎样借助Python语言完成与政务微信平台对接的主要步骤概述。当然,这只是冰山一角,更多高级特性和细节还需深入研究相关资料和技术文档。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值