• 微信开发工具类


    
    import net.sf.json.JSONObject;
    import org.apache.commons.httpclient.util.HttpURLConnection;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.activation.MimetypesFileTypeMap;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.URL;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    /**
     * @Package com.XXX.app
     * @Description: ${todo}
     * @Author: admin
     * @Date: 2018/5/1410:44
     */
    public class WeixinUtil {
    
        private static final String SERVLET_POST = "POST" ;
        private static final String SERVLET_GET = "GET" ;
        private static final String SERVLET_DELETE = "DELETE" ;
        private static final String SERVLET_PUT = "PUT" ;
    
        //微信配置
        private static  final  String APP_ID = "";
        private static  final  String APP_SECRECT = "";
        //上传文件配置
        private  static  final String UPLOAD_FILE_SAVE_PATH = "";
        private  static  final  String UPLOAD_FILE_SAVE_PATHUPLOAD_FILE_SAVE_PATH = "";
    
    
    
        /**
         * 参数格式化
         * @param paramMap
         * @return
         */
        private static String prepareParam(Map<String,Object> paramMap){
            StringBuffer sb = new StringBuffer();
            if(paramMap.isEmpty()){
                return "" ;
            }else{
                for(String key: paramMap.keySet()){
                    String value = (String)paramMap.get(key);
                    if(sb.length()<1){
                        sb.append(key).append("=").append(value);
                    }else{
                        sb.append("&").append(key).append("=").append(value);
                    }
                }
                return sb.toString();
            }
        }
    
    
        /**
         * 上传图片
         *
         * @param urlStr
         * @param textMap
         * @param fileMap
         * @return
         */
        @SuppressWarnings({ "restriction", "rawtypes" })
        public static String formUpload(String urlStr, Map<String, String> textMap,
                                        Map<String, String> fileMap) {
            String res = "";
            HttpURLConnection conn = null;
            String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
            try {
                URL url = new URL(urlStr);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(30000);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data; boundary=" + BOUNDARY);
    
                OutputStream out = new DataOutputStream(conn.getOutputStream());
                // text
                if (textMap != null) {
                    StringBuffer strBuf = new StringBuffer();
                    Iterator iter = textMap.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        String inputName = (String) entry.getKey();
                        String inputValue = (String) entry.getValue();
                        if (inputValue == null) {
                            continue;
                        }
                        strBuf.append("
    ").append("--").append(BOUNDARY).append(
                                "
    ");
                        strBuf.append("Content-Disposition: form-data; name=""
                                + inputName + ""
    
    ");
                        strBuf.append(inputValue);
                    }
                    out.write(strBuf.toString().getBytes());
                }
    
                // file
                if (fileMap != null) {
                    Iterator iter = fileMap.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        String inputName = (String) entry.getKey();
                        String inputValue = (String) entry.getValue();
                        if (inputValue == null) {
                            continue;
                        }
                        File file = new File(inputValue);
                        String filename = file.getName();
                        String contentType = new MimetypesFileTypeMap()
                                .getContentType(file);
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        }
                        if (contentType == null || contentType.equals("")) {
                            contentType = "application/octet-stream";
                        }
    
                        StringBuffer strBuf = new StringBuffer();
                        strBuf.append("
    ").append("--").append(BOUNDARY).append(
                                "
    ");
                        strBuf.append("Content-Disposition: form-data; name=""
                                + inputName + ""; filename="" + filename
                                + ""
    ");
                        strBuf.append("Content-Type:" + contentType + "
    
    ");
    
                        out.write(strBuf.toString().getBytes());
    
                        DataInputStream in = new DataInputStream(
                                new FileInputStream(file));
                        int bytes = 0;
                        byte[] bufferOut = new byte[1024];
                        while ((bytes = in.read(bufferOut)) != -1) {
                            out.write(bufferOut, 0, bytes);
                        }
                        in.close();
                    }
                }
    
                byte[] endData = ("
    --" + BOUNDARY + "--
    ").getBytes();
                out.write(endData);
                out.flush();
                out.close();
    
                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("
    ");
                }
                res = strBuf.toString();
                reader.close();
                reader = null;
            } catch (Exception e) {
                System.out.println("发送POST请求出错。" + urlStr);
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }
            }
            return res;
        }
    
        /**
         * 上传图片
         *
         * @param urlStr
         * @param textMap
         * @param fileMap
         * @return
         */
        @SuppressWarnings({ "restriction", "rawtypes" })
        public static String uploadFile(String urlStr, Map<String, String> textMap,
                                        MultipartFile mfile) {
            String res = "";
            HttpURLConnection conn = null;
            String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
            try {
                URL url = new URL(urlStr);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(30000);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data; boundary=" + BOUNDARY);
    
                OutputStream out = new DataOutputStream(conn.getOutputStream());
                // text
                if (textMap != null) {
                    StringBuffer strBuf = new StringBuffer();
                    Iterator iter = textMap.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        String inputName = (String) entry.getKey();
                        String inputValue = (String) entry.getValue();
                        if (inputValue == null) {
                            continue;
                        }
                        strBuf.append("
    ").append("--").append(BOUNDARY).append(
                                "
    ");
                        strBuf.append("Content-Disposition: form-data; name=""
                                + inputName + ""
    
    ");
                        strBuf.append(inputValue);
                    }
                    out.write(strBuf.toString().getBytes());
                }
    
                // file
                if (mfile != null) {
    
                    String filename = mfile.getOriginalFilename();
                    String contentType = new MimetypesFileTypeMap()
                            .getContentType(mfile.getContentType());
                    System.out.println(contentType);
    
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("
    ").append("--").append(BOUNDARY).append(
                            "
    ");
                    strBuf.append("Content-Disposition: form-data; name="media"; filename="" + filename
                            + ""
    ");
                    strBuf.append("Content-Type:" + contentType + "
    
    ");
    
                    out.write(strBuf.toString().getBytes());
    
                    DataInputStream in = new DataInputStream(mfile.getInputStream());
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
    
                byte[] endData = ("
    --" + BOUNDARY + "--
    ").getBytes();
                out.write(endData);
                out.flush();
                out.close();
    
                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("
    ");
                }
                res = strBuf.toString();
                reader.close();
                reader = null;
            } catch (Exception e) {
                System.out.println("发送POST请求出错。" + urlStr);
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }
            }
            return res;
        }
        /**
         * POST json格式输出
         * @param sendurl
         * @param data
         * @return
         */
        public static String sendInfo(String sendurl, String data) {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(sendurl);
            StringEntity myEntity = new StringEntity(data,
                    ContentType.APPLICATION_JSON);// 构造请求数据
            post.setEntity(myEntity);// 设置请求体
            String responseContent = null; // 响应内容
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    responseContent = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null)
                        response.close();
    
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (client != null)
                            client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return responseContent;
        }
    
    
        /**
         * 模拟POST提交数据
         * @param urlStr
         * @param paramMap
         * @throws Exception
         */
        @SuppressWarnings("unused")
        public static void  doPost(String urlStr,Map<String,Object> paramMap ) throws Exception{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(SERVLET_POST);
            String paramStr = prepareParam(paramMap);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(paramStr.toString().getBytes("utf-8"));
            os.close();
    
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line ;
            String result ="";
            while( (line =br.readLine()) != null ){
                result += "/n"+line;
            }
            br.close();
    
        }
    
        /**
         * 模拟 GET提交数据
         * @param urlStr
         * @param paramMap
         * @return
         * @throws Exception
         */
        public static String  doGet(String urlStr,Map<String,Object> paramMap ) throws Exception{
            String paramStr = prepareParam(paramMap);
            if(paramStr == null || paramStr.trim().length()<1){
    
            }else{
                urlStr +="?"+paramStr;
            }
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(SERVLET_GET);
            conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");
    
            conn.connect();
            if(conn.getResponseCode() == 200){
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line ;
                String result ="";
                while( (line =br.readLine()) != null ){
                    result += line;
                }
                br.close();
                return result;
            }else{
                /* Map<String,Object> map = new HashMap<String,Object>();
                 map.put("errcode", "40001");
                 map.put("errmsg", "接口响应失败");
                 JSONObject.fromObject(map);*/
                String re = "{"errcode":200,"errmsg":"接口响应失败"}";
                return re;
            }
    
    
        }
    
        @SuppressWarnings("unused")
        public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(SERVLET_PUT);
            String paramStr = prepareParam(paramMap);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(paramStr.toString().getBytes("utf-8"));
            os.close();
    
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line ;
            String result ="";
            while( (line =br.readLine()) != null ){
                result += "/n"+line;
            }
            br.close();
    
        }
    
        public static void doDelete(String urlStr,Map<String,Object> paramMap) throws Exception{
            String paramStr = prepareParam(paramMap);
            if(paramStr == null || paramStr.trim().length()<1){
    
            }else{
                urlStr +="?"+paramStr;
            }
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod(SERVLET_DELETE);
            if(conn.getResponseCode() ==200){
                System.out.println("成功");
            }else{
                System.out.println(conn.getResponseCode());
            }
        }
    
    
        /**
         * 根据APPID和APPSECRECT获取token
         * @param appId
         * @param appSecret
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> getToken(String appId ,String appSecret,String code){
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("appid", appId);
            param.put("secret", appSecret);
            param.put("code", code);
            param.put("grant_type", "authorization_code");
            try {
                String result = WeixinUtil.doGet(url,param);
                if(result!=null && result!=""){
                    Map<String,Object> map = JSONObject.fromObject(result);
                    if(map.containsKey("errcode")){
                        String errcode = map.get("errcode").toString();
                        String errmsg = map.get("errmsg").toString();
                        back.put("errcode", errcode);
                        back.put("errmsg", errmsg);
                        back.put("token", "");
                    }else{
                        back = map;
                        back.put("errcode", "0");
                    }
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口响应失败");
                    back.put("token", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
    
        }
    
    
        /**
         * 根据APPID和APPSECRECT获取token
         * @param appId
         * @param appSecret
         * @return
         *
         * {
         * "access_token":"ACCESS_TOKEN",
         * "expires_in":7200,
         * "refresh_token":"REFRESH_TOKEN",
         * "openid":"OPENID",
         * "scope":"SCOPE"
         * }
         *
         *
         */
        @SuppressWarnings({ "unchecked", "unused" })
        public static Map<String,Object> refresh_token(String appId,String refresh_token){
            String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("appid", appId);
            param.put("refresh_token", refresh_token);
            param.put("grant_type", "refresh_token");
            try {
                String result = WeixinUtil.doGet(url,param);
                if(result!=null && result!=""){
                    Map<String,Object> map = JSONObject.fromObject(result);
                    if(map.containsKey("errcode")){
                        String errcode = map.get("errcode").toString();
                        String errmsg = map.get("errmsg").toString();
                        back.put("errcode", errcode);
                        back.put("errmsg", errmsg);
                        back.put("token", "");
                    }else{
                        String access_token = map.get("access_token").toString();
                        //String expires_in = map.get("expires_in").toString();
                        back = map;
                        back.put("errcode", "0");
                        //back.put("token", access_token);
                        //back.put("expires_in", expires_in);
                    }
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口响应失败");
                    back.put("token", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
    
        }
    
        /**
         * 根据access_token和openid获取用户信息
         * @param access_token
         * @param openid
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> snsuserinfo(String access_token ,String openid){
            String url = "https://api.weixin.qq.com/sns/userinfo";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("access_token", access_token);
            param.put("openid", openid);
            param.put("lang", "zh_CN");
            try {
                String result = WeixinUtil.doGet(url,param);
                if(result!=null && result!=""){
                    Map<String,Object> map = JSONObject.fromObject(result);
                    if(map.containsKey("errcode")){
                        String errcode = map.get("errcode").toString();
                        String errmsg = map.get("errmsg").toString();
                        back.put("errcode", errcode);
                        back.put("errmsg", errmsg);
                        back.put("token", "");
                    }else{
    
                        back = map;
                        back.put("errcode", "0");
    
                    }
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口响应失败");
                    back.put("token", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
    
        }
    
    
        /**
         * 根据APPID和APPSECRECT获取token
         * @param appId
         * @param appSecret
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> getToken(){
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("appid", APP_ID);
            param.put("secret", APP_SECRECT);
            param.put("grant_type", "client_credential");
            try {
                String result = WeixinUtil.doGet(url,param);
                if(result!=null && result!=""){
                    Map<String,Object> map = JSONObject.fromObject(result);
                    if(map.containsKey("errcode")){
                        String errcode = map.get("errcode").toString();
                        String errmsg = map.get("errmsg").toString();
                        back.put("errcode", errcode);
                        back.put("errmsg", errmsg);
                        back.put("token", "");
                    }else{
                        String access_token = map.get("access_token").toString();
                        //String expires_in = map.get("expires_in").toString();
                        back.put("errcode", "0");
                        back.put("token", access_token);
                        //back.put("expires_in", expires_in);
                    }
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口相应失败");
                    back.put("token", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
    
        }
    
        /**
         * 根据APPID和APPSECRECT获取token
         * @param appId
         * @param appSecret
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> getticket(String access_token,String type){
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("access_token", access_token);
            param.put("type", type);
            try {
                String result = WeixinUtil.doGet(url,param);
    
                if(result!=null && result!=""){
                    Map<String,Object> map = JSONObject.fromObject(result);
                    back = map;
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口相应失败");
                    back.put("ticket", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
    
        }
    
        /**
         * 获取素材总数
         * @param token
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> get_materialcount(String token){
            String url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount";
            Map<String,Object> param = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            param.put("access_token", token);
            try {
                String result = WeixinUtil.doGet(url,param);
                if(result!=null && result!=""){
                    back = JSONObject.fromObject(result);
    
                }else{
                    back.put("errcode", "601");
                    back.put("errmsg", "接口响应失败");
                    back.put("token", "");
                }
    
    
            } catch (Exception e) {
                back.put("errcode", "602");
                back.put("errmsg", "程序异常");
                back.put("token", "");
                e.printStackTrace();
            }
            return back;
        }
    
        /**
         * 获取素材列表
         * @param token
         * @param param 参数示例 {"type":"news","offset":0,"count":20}
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> batchget_material(String token,String json){
            String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+token;
            //String json = param.toString();
            Map<String,Object> map = new HashMap<String,Object>();
            try {
                String result = sendInfo(url, json);
                map = JSONObject.fromObject(result);
    
            } catch (Exception e) {
                map.put("errcode", "602");
                map.put("errmsg", "程序异常");
                map.put("token", "");
                e.printStackTrace();
            }
            return map;
        }
    
    
        /**
         * 添加素材
         * @param token
         * @param filepath
         * @param type
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> add_material(String token,MultipartFile file, String type){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "http://api.weixin.qq.com/cgi-bin/material/add_material?access_token="+token;
            Map<String, String> textMap = new HashMap<String, String>();
            textMap.put("type", type);
            String ret = uploadFile(urlStr, textMap, file);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
    
        /**
         * 删除图文素材
         * @param token
         * @param param
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> delMaterail(String token, Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
        /**
         * 添加图文素材
         * @param token
         * @param param
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> add_news(String token, Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
        /**
         * 下载微信图片素材
         * @param url
         * @param data
         * @return
         */
        public static String downImage(String url, String data) {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            StringEntity myEntity = new StringEntity(data,
                    ContentType.APPLICATION_JSON);// 构造请求数据
            post.setEntity(myEntity);// 设置请求体
            String responseContent = null; // 响应内容
            String extension = ".jpg";
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println(response.getEntity().toString());
                    HttpEntity entity = response.getEntity();
                    System.out.println(entity.getContent());
                    BufferedImage bi = ImageIO.read(entity.getContent());
    
                    String key = UUID.randomUUID().toString();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
                    String save_path = sdf.format(new Date());
                    String filepath=UPLOAD_FILE_SAVE_PATHUPLOAD_FILE_SAVE_PATH + "logo/"+save_path;
                    StringBuffer filePath = new StringBuffer(filepath);
                    File dir = new File(filePath.toString());//文件保存路径
                    if(!dir.exists()){
                        dir.mkdirs();
                    }
                    //新文件名
                    filePath.append(key).append(extension);
                    System.out.println(filePath);
                    File out = new File(filePath.toString());
                    ImageIO.write(bi, "jpg", out);
                    responseContent = "logo/"+save_path+key+extension;
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null)
                        response.close();
    
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (client != null)
                            client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return responseContent;
        }
        @SuppressWarnings("unchecked")
        public static Map<String,Object> getfiles(String url){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> param = new HashMap<String,Object>();
            String ret;
            try {
                ret = WeixinUtil.doGet(url,param);
                back = JSONObject.fromObject(ret);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return back;
        }
    
        /**
         * 获取用户列表
         * @param token
         * @param next
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> userlist(String token,String next){
            Map<String,Object> paramMap = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/user/get";
    
            try {
                paramMap.put("access_token", token);
                if(next!=null){
                    paramMap.put("next_openid", next);
                }
                String res = WeixinUtil.doGet(urlStr, paramMap);
                back = JSONObject.fromObject(res);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return back;
    
        }
        /**
         * 获取用户信息
         * @param token
         * @param openid
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> userinfo(String token,String openid){
            Map<String,Object> paramMap = new HashMap<String,Object>();
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/user/info";
    
            try {
                paramMap.put("access_token", token);
                paramMap.put("lang", "zh_CN");
                if(openid!=null){
                    paramMap.put("openid", openid);
                }
                String res = WeixinUtil.doGet(urlStr, paramMap);
                back = JSONObject.fromObject(res);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return back;
    
        }
    
        /**
         * 创建分组
         * POST数据格式:json
         * POST数据例子:{"group":{"name":"test"}}
         * @param token
         * @param param
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> groupscreate(String token, String value){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> groups = new HashMap<String,Object>();
            Map<String,Object> group = new HashMap<String,Object>();
            group.put("name", value);
            groups.put("group", group);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token="+token;
            String json = JSONObject.fromObject(groups).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
    
        /**
         * 修改分组
         * POST数据格式:json
         * POST数据例子:{"group":{"name":"test"}}
         * @param token
         * @param param
         * @return  {"errcode":0,"errmsg":"ok"}
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> groupsupdate(String token, Integer id, String value){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> groups = new HashMap<String,Object>();
            Map<String,Object> group = new HashMap<String,Object>();
            group.put("name", value);
            group.put("id", id);
            groups.put("group", group);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token="+token;
            String json = JSONObject.fromObject(groups).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
    
        /**
         * 删除分组
         * POST数据格式:json
         * POST数据例子:{"group":{"id":106}}
         * @param token
         * @param param
         * @return  {"errcode":0,"errmsg":"ok"}
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> groupsdelete(String token,Integer id){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> groups = new HashMap<String,Object>();
            Map<String,Object> group = new HashMap<String,Object>();
            group.put("id", id);
            groups.put("group", group);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token="+token;
            String json = JSONObject.fromObject(groups).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
    
    
        }
    
        /**
         * 查询所有分组
         * @param token
         * @return {"groups": [{ "id": 0, "name": "未分组","count": 72596},...]}
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> groupsget(String token){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("access_token", token);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/get";
            String ret;
            try {
                ret = doGet(urlStr, param);
                back = JSONObject.fromObject(ret);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return back;
        }
    
        /**
         * 下载素材图片
         * @param media_id
         * @param token
         * @return
         */
        public static String downmedia(String media_id,String token){
            String key = null;
            //String extension = ".jpg";
            String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="+token;
            String json = "{"media_id":""+media_id+""}";
            key = downImage(url, json);
    
            return key;
        }
    
    
        public static String downqrcode(String media_id,String ticket){
            String key = null;
            //String extension = ".jpg";
            String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
            String json = "{"media_id":""+media_id+""}";
            key = downImage(url, json);
    
            return key;
        }
    
        /**
         * 查询用户所在分组
         * @param token
         * @param openid
         * POST数据格式:json
         * POST数据例子:{"openid":"od8XIjsmk6QdVTETa9jLtGWA6KBc"}
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object>  groupsgetid(String token,String openid){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> groups = new HashMap<String,Object>();
            groups.put("openid", openid);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+token;
            String json = JSONObject.fromObject(groups).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
        /**
         * 移动用户分组
         * POST数据格式:json
         * POST数据例子:{"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}
         * @param token
         * @param openid
         * @param grouid
         * @return {"errcode": 0, "errmsg": "ok"}
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object>  groupsmemeberupdate(String token,String openid,Integer grouid){
            Map<String,Object> back = new HashMap<String,Object>();
            Map<String,Object> groups = new HashMap<String,Object>();
            groups.put("openid", openid);
            groups.put("to_groupid", grouid);
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+token;
            String json = JSONObject.fromObject(groups).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
        /**
         * 批量移动用户分组
         * POST数据格式:json
         * POST数据例子:{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}
         * @param token
         * @param param
         * @return {"errcode": 0, "errmsg": "ok"}
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object>  groupsmemeberbatchupdate(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
    
        /**
         *
         * @param token
         * @param param
         * @return
         */
        @SuppressWarnings("unchecked")
        public static Map<String,Object> sendall(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
        @SuppressWarnings("unchecked")
        public static Map<String,Object> send(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
        @SuppressWarnings("unchecked")
        public static Map<String,Object> preview(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
    
        @SuppressWarnings("unchecked")
        public static Map<String,Object> messdelete(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
        public static Map<String, String> sign(String jsapi_ticket, String url) {
            Map<String, String> ret = new HashMap<String, String>();
            String nonce_str = create_nonce_str();
            String timestamp = create_timestamp();
            String string1;
            String signature = "";
    
            //注意这里参数名必须全部小写,且必须有序
            string1 = "jsapi_ticket=" + jsapi_ticket +
                    "&noncestr=" + nonce_str +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
            //System.out.println(string1);
    
            try
            {
                MessageDigest crypt = MessageDigest.getInstance("SHA-1");
                crypt.reset();
                crypt.update(string1.getBytes("UTF-8"));
                signature = byteToHex(crypt.digest());
            }
            catch (NoSuchAlgorithmException e)
            {
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
    
            ret.put("url", url);
            ret.put("jsapi_ticket", jsapi_ticket);
            ret.put("nonceStr", nonce_str);
            ret.put("timestamp", timestamp);
            ret.put("signature", signature);
    
            return ret;
        }
    
        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;
        }
    
        private static String create_nonce_str() {
            return UUID.randomUUID().toString();
        }
    
        private static String create_timestamp() {
            return Long.toString(System.currentTimeMillis() / 1000);
        }
    
    
    
        public static void testsend(String[] args){
            String token = "UPTPwZDO--BMDWGhbaCuo6WZKkukZVRRCdFiZLhp0xvkaTT2QWbzv8im_f5r1EWwVyks6bVjPiUoBN1RAnPHkhG8ECHkQRNVRthcVTK4afQ";
            String media_id = "Pbz69tsaX-ApsEx-phLYrshzVklx4CXbdQGKSYX8Wf4";
            Map<String,Object> params = new HashMap<String,Object>();
            //String touser = "olDxquNH-rq1G8ICKCwrbkAOe2aA";
            Map<String,Object> mpnews = new HashMap<String,Object>();
            List<String> touser = new ArrayList<String>();
            touser.add("olDxquNH-rq1G8ICKCwrbkAOe2aA");
            touser.add("olDxquEEPUh5D8NZfMmhBo9jRl8A");
            touser.add("olDxquJJ_IRQ8k4v_Pm6QRLZ_mlA");
    
            mpnews.put("media_id", media_id);
            params.put("touser", touser);
            params.put("mpnews", mpnews);
            params.put("msgtype", "mpnews");
            Map<String,Object > back = send(token,params);
            System.out.println(back);
        }
        public static void testsendall(String[] args){
            String token = "VImhFxajkULI3av18oZ_klHb1uHRHES5qbgo20GG2bwATAd34wROSqDlp5dDuuvIZsK5qCI6ZbEqILCGlOMnijsNNIbR9JpVBxw_LDZJ5Uw";
            String media_id = "Pbz69tsaX-ApsEx-phLYrshzVklx4CXbdQGKSYX8Wf4";
            Map<String,Object> params = new HashMap<String,Object>();
            Map<String,Object> mpnews = new HashMap<String,Object>();
            Map<String,Object> filter = new HashMap<String,Object>();
            filter.put("is_to_all", false);
            filter.put("group_id", "101");
            mpnews.put("media_id", media_id);
    
            params.put("filter", filter);
            params.put("mpnews", mpnews);
            params.put("msgtype", "mpnews");
            Map<String,Object > back = sendall(token,params);
            System.out.println(back);
        }
    
        public static void testpreview(String[] args){
            String token = "VImhFxajkULI3av18oZ_klHb1uHRHES5qbgo20GG2bwATAd34wROSqDlp5dDuuvIZsK5qCI6ZbEqILCGlOMnijsNNIbR9JpVBxw_LDZJ5Uw";
            String media_id = "Pbz69tsaX-ApsEx-phLYrshzVklx4CXbdQGKSYX8Wf4";
            Map<String,Object> params = new HashMap<String,Object>();
            String touser = "olDxquNH-rq1G8ICKCwrbkAOe2aA";
            Map<String,Object> mpnews = new HashMap<String,Object>();
            mpnews.put("media_id", media_id);
            params.put("touser", touser);
            params.put("mpnews", mpnews);
            params.put("msgtype", "mpnews");
            Map<String,Object > back = preview(token,params);
            System.out.println(back);
        }
    
        //创建菜单
        @SuppressWarnings("unchecked")
        public static Map<String,Object> createmenu(String token,Map<String,Object> param){
            Map<String,Object> back = new HashMap<String,Object>();
            String urlStr = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
            String json = JSONObject.fromObject(param).toString();
            String ret  = sendInfo(urlStr, json);
            back = JSONObject.fromObject(ret);
            return back;
        }
        //main方法测试
        public static void main(String[] args){
            //第一步:根据APPID和APPSECRECT获取token
            String token = getToken().get("token").toString();
            //第二步:执行相关方法
            Map<String,Object> back =  WeixinUtil.groupsmemeberupdate(token,"orBxRuGoYCdu6x35Q81e9Potg7vM",111);
            System.out.println(back);
        }
    }
    
  • 相关阅读:
    .net core consul
    numpy
    Cordova各个插件使用介绍系列(七)—$cordovaStatusbar手机状态栏显示
    ionic 的缓存 和局部刷新
    ionic 项目中添加modal的步骤流程
    ionic 项目中创建侧边栏的具体流程分4步简单学会
    Cordova各个插件使用介绍系列(八)—$cordovaCamera筛选手机图库图片并显示
    python-16: time 模块 之一
    python-16:模块 包
    c-3:位运算:位运算基本用法
  • 原文地址:https://www.cnblogs.com/jpfss/p/9034927.html
Copyright © 2020-2023  润新知