企业微信获取JS-SDK并下载临时素材

前言

注意:
1.corpid是企业微信的ID, corpsecret是应用程序的;需要应用配置网页授权可信任域名,下载完文件后,把已下载的文件放置到域名根目录下(需要管理员权限,查看文档具体说明。)
2.小程序获取方法其实是一样的,只是地址不一样,可以看一下微信文档说明。

在这里插入图片描述
在这里插入图片描述

1.企业微信获取access_token
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=corpid&corpsecret=corpsecret

/**
     * 企业微信access_token
     * @return
     */
    public static String getQyAccess_token() throws Exception {
        String nowtime = DateHelper.getNow();
        //小于半个小时直接返回之前的 qywx_accesstoken
        if(StringHelper.isNotEmpty(qywx_accesstoken) && DateHelper.getDateSecond(qywx_accesstokentime,nowtime)<1800){
            return qywx_accesstoken;
        }
        qywx_accesstokentime = nowtime;
        HttpURLConnection conn = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        JSONObject jsonObject = null;
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;
            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            inputStreamReader = new InputStreamReader(conn.getInputStream(), "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = JSONObject.fromObject(buffer.toString());
            String access_token = jsonObject.getString("access_token");
            //System.out.println("----------------------Access_token---------------------------" + access_token);
            return access_token;
        } catch (Exception e) {
            System.out.println("----------------------Access_tokenError---------------------------" + jsonObject);
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

2.获取jsticket
https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=access_token

/**
     * 获取jsticket的执行体
     *
     * @param access_token
     * @return
     */
    public static String getTicket(String access_token) throws Exception {
        String nowtime = DateHelper.getNow();
        //小于半个小时直接返回之前的 ticket
        if(StringHelper.isNotEmpty(ticket) && DateHelper.getDateSecond(ticket_time,nowtime)<1800){
            return ticket;
        }
        ticket_time = nowtime;
        HttpURLConnection conn = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        JSONObject jsonObject = null;
        try {
            String getticket = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+access_token;
            String url = String.format(getticket, APPID, APPSECRET);
            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            inputStreamReader = new InputStreamReader(conn.getInputStream(), "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = JSONObject.fromObject(buffer.toString());
            String ticket = jsonObject.getString("ticket");
            System.out.println("----------------------ticket---------------------------" + ticket);
            return ticket;
        } catch (Exception e) {
            System.out.println("----------------------ticketError---------------------------" + jsonObject);
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

3.获取前端jssdk页面配置需要用到的配置参数

/**
     * 前端jssdk页面配置需要用到的配置参数
     *
     * @param url
     * @param ticket
     * @return
     * @throws Exception
     */
    public static Map<String, String> getSignature(String url, String ticket,String appid) throws Exception {
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        // 注意这里参数名必须全部小写,且必须有序
        String string1 = "jsapi_ticket=" + ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        String signature = byteToHex(crypt.digest());
        HashMap<String, String> jssdk = new HashMap<String, String>();
        jssdk.put("appId", appid);
        jssdk.put("timestamp", timestamp);
        jssdk.put("nonceStr", noncestr);
        jssdk.put("signature", signature);
        return jssdk;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

4.获取微信临时素材
https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=access_token&media_id=mediaId

/**
     * 获取微信临时素材
     *
     * @param mediaId
     * @return
     */
    public static InputStream downloadMedia(String access_token, String mediaId) {
        URLConnection conn = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        String fileSize = "";
        try {
            String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+mediaId;
            URL realUrl = new URL(requestUrl);
            conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded; charset=utf-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8"); //
            conn.setRequestProperty("contentType", "utf-8");

            //获取网络流的头部信息
            Map<String, List<String>> maps = conn.getHeaderFields();
            for (String key : maps.keySet()) {
                System.out.println(key + "---> " + maps.get(key));
                if ("Content-Length".equals(key)) {
                    fileSize = maps.get(key).get(0);//获取文件大小
                }
            }
            // 获取网络流的内容
            bis = new BufferedInputStream(conn.getInputStream());
            byte[] data = getByte(bis); // 获取当前条目的字节数组
            is = new ByteArrayInputStream(data); // 把当前条目的字节数据转换成Inputstream流
            return is ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取条目byte[]字节
     *
     * @param is
     * @return
     */
    public static byte[] getByte(InputStream is) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            byte[] buf = null;
            int length = 0;
            while ((length = is.read(temp, 0, 1024)) != -1) {
                bout.write(temp, 0, length);
            }
            buf = bout.toByteArray();
            bout.close();
            return buf;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

5. 欢迎留言 https://blog.csdn.net/jia814583973/


版权声明:本文为jia814583973原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。